0

Is there a regular expression to match a numeric range, e.g. 1 - 20?

If so, is it possible to ensure that the left value is always less than the right value? It wouldn't make sense to have a range e.g. 20 - 1 or 15 - 5

DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • 1
    Unfortunately I don't think it's possible, or not without a horrifically long regex at least (although I would be happy to be proved wrong). – Meep3D Aug 09 '12 at 09:52
  • 1
    It is most likely *possible*, but that does not mean you should ever do it. Regular expressions are a [*completely wrong* choice](http://stackoverflow.com/a/4098123/395760) for this problem. –  Aug 09 '12 at 09:54
  • You should use numerical operators for comparing digits. Regular expressions simply match patterns. – npinti Aug 09 '12 at 09:59
  • There are some utilities that will generate such a range regex for you. Try http://utilitymill.com/utility/Regex_For_Range – borrible Aug 09 '12 at 10:05

2 Answers2

0

As the commentors note: if this is possible in a regex it will be very hard. There is no direct support to perform arithmetical comparisons (including greater than) in a regex.

Better to use a regex to validate the format and capture the two numbers. If the regex matches then use the host language to convert the captures into numbers and compare.

Richard
  • 106,783
  • 21
  • 203
  • 265
0

Yes you can do that. You can ensure that a given number is smaller than another number in the same text.

This regex tests whether the first number is smaller than the next number: Format: XXX,YYY

XXX < YYY:

\b(?:[1-9](?<open>\B\d)+\d*,(?<close-open>\d)+(?(open)(?!))\b
|
(?<prefix>\d*)(?:(?<g0>0)|(?<g1>1)|(?<g2>2)|(?<g3>3)|(?<g4>4)|(?<g5>5)|(?<g6>6)|(?<g7>7)|(?<g8>8)|(?<g9>9))(?<suffix>\d)*,\k<prefix>(?(g0)(?!)|(?(g1)0|(?(g2)[01]|(?(g3)[0-2]|(?(g4)[0-3]|(?(g5)[0-4]|(?(g6)[0-5]|(?(g7)[0-6]|(?(g8)[0-7]|(?(g9)[0-8]))))))))))(?<suffix2-suffix>\d)*(?(suffix)(?!)))\b

XXX > YYY:

(?<open>\B\d|\b[1-9])+,[1-9](?<close-open>\d)+(?(open)(?!))\d*\b
|
(?<prefix>\d*)(?:(?<g0>0)|(?<g1>1)|(?<g2>2)|(?<g3>3)|(?<g4>4)|(?<g5>5)|(?<g6>6)|(?<g7>7)|(?<g8>8)|(?<g9>9))(?<suffix>\d)*,\k<prefix>(?(g0)[1-9]|(?(g1)[2-9]|(?(g2)[3-9]|(?(g3)[4-9]|(?(g4)[5-9]|(?(g5)[6-9]|(?(g6)[7-9]|(?(g7)[89]|(?(g8)9|(?(g9)(?!)))))))))))(?<suffix2-suffix>\d)*(?(suffix)(?!))

If you want to use - as separator you only have to replace the , with - in this regex. This regex was created and tested using C# regex.

Sebastian Schumann
  • 3,204
  • 19
  • 37