Regex to exclude a range of numbers

Viewed 853

I am trying to exclude all decimal numbers below 200. For example:

50.123 invalid
150.103 invalid
205.111 valid

With the ([0-9][0-9])|(1[0-9][0-9])\.* reg expression, I am getting the following results:

50.123 valid but should be invalid
150.103 invalid
205.111 valid

Can anyone tell me why any decimal number < 100 is valid?

4 Answers

You may use this regex to validate all your numbers below 200:

^[01]?[0-9]{1,2}(?:\.[0-9]+)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • [01]?: Match 0 or 1 or nothing
  • [0-9]{1,2}: Match 1 or 2 digits
  • (?:\.[0-9]+)?: Optionally match . followed by 1+ digits
  • $: End

Looking at the fact you want to exclude numbers below 200 and your sample data that showed invalid examples, I think you would need:

^(?:[2-9]\d{2,}|1\d{3,})(?:\.\d+)?$

See the online demo

  • ^ - Start string anchor.
  • (?: - 1st Non-capture group:
    • [2-9]\d{2,} - Match number ranging from 2-9 followed 2+ digits.
    • | - Or:
    • 1\d{3,} - A 1 followed by at 3+ digits.
    • ) - Close non-capture group.
  • (?: - Open 2nd non-capture group:
    • \.\d+ - A literal dot followed by 1+ digits.
    • )? - Close 2nd non-capture group and make it optional.
  • $ - End string anchor.
/(?<!\d)
(\d{2}|1\d{2})\.\d+/g

\d{2}: 2 digits

(?<!\d): not have a digit before it => avoid 05.111 in 205.111 being matched

I tried your regex but it has problems,so I came up with another solution.

Thank you for the answers (which all work correctly).

Bohemian was also correct in saying that:

it ends with \.* but should end with \..* or more precisely \.\d*

So I edited my regular expression to the following which now works fine:

([0-9][0-9]\.\d*)|(1[0-9][0-9]\.\d*)

Related