Skip to content
Advertisement

Regular expression for digits, decimals, and fractions

How can I create a regex that allows whole numbers, decimals, fractions, and fractions with decimals? The string can also have optional text, only at the end. So far I have this:

JavaScript

This allows double decimals in a whole number(ie: ‘23.23.23’), which I do not want. Can I modify this regex to allow two decimal points only if it is separated by a ‘/’?

Here are some examples that can pass:

  • 23.23/100km
  • 1/3
  • .23km
  • 1.mi
  • 1.2/2.1kg

Some examples that shouldn’t pass:

  • 1a3km
  • 12.12.12
  • 1.2.3/12.13km
  • 12km/12.44km

Advertisement

Answer

Use

JavaScript

See proof. This expression disallows three numbers that have a period between one another thanks to (?!.*d+(?:.d+){2}) negative lookahead.

EXPLANATION

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement