[regex] Regex to match 2 digits, optional decimal, two digits

I've spent half an hour trying to get this, maybe someone can come up with it quickly.

I need a regular expression that will match one or two digits, followed by an optional decmial point, followed by one or two digits.

For example, it should match these strings in their entirety:

3
33
.3
.33
33.3
33.33

and NOT match anything with more than 2 digits before or after the decmial point.

This question is related to regex

The answer is


you can use

let regex = new RegExp( ^(?=[0-9.]{1,${maxlength}}$)[0-9]+(?:\.[0-9]{0,${decimal_number}})?$ );

where you can decide the maximum length and up to which decimal point you want to control the value

Use ES6 String interpolation to wrap the variables ${maxlength} and ${decimal_number}.


(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])

Matches:

  • Your examples
  • 33.

Does not match:

  • 333.33
  • 33.333

  \d{1,}(\.\d{1,2})|\d{0,9}

tested in https://regexr.com/

matches with numbers with 2 decimals or just one, or numbers without decimals.

You can change the number or decimals you want by changing the number 2


^\d{0,2}\.?\d{1,2}$

Try this

\d{1,2}\.?(\.\d{1,2})?

^(\d{0,2}\\.)?\d{1,2}$

\d{1,2}$ matches a 1-2 digit number with nothing after it (3, 33, etc.), (\d{0,2}\.)? matches optionally a number 0-2 digits long followed by a period (3., 44., ., etc.). Put them together and you've got your regex.


A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$

You mentioned that you want the regex to match each of those strings, yet you previously mention that the is 1-2 digits before the decimal?

This will match 1-2 digits followed by a possible decimal, followed by another 1-2 digits but FAIL on your example of .33

\d{1,2}\.?\d{1,2}

This will match 0-2 digits followed by a possible deciaml, followed by another 1-2 digits and match on your example of .33

\d{0,2}\.?\d{1,2}

Not sure exactly which one you're looking for.


Following is Very Good Regular expression for Two digits and two decimal points.

[RegularExpression(@"\d{0,2}(\.\d{1,2})?", ErrorMessage = "{0} must be a Decimal Number.")]

To build on Lee's answer, you need to anchor the expression to satisfy the requirement of not having more than 2 numbers before the decimal.

If each number is a separate string, you can use the string anchors:

^\d{0,2}(\.\d{1,2})?$

If each number is within a string, you can use the word anchors:

\b\d{0,2}(\.\d{1,2})?\b