Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match numbers between X and Y with regexp?

Tags:

regex

I would like to match with RegExp a number between X and Y. Is that possible?

([0-9]+) will match any number, how could I do to match a number between, for instance, 110 and 2234?

like image 448
barredo Avatar asked Mar 24 '09 07:03

barredo


People also ask

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

How do I use regex to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Can regex be used for numbers?

Real number regex can be used to validate or exact real numbers from a string.

What is regex pattern matching?

A regular expression is a pattern of text that consists of ordinary characters, for example, letters a through z, and special characters. Character(s) Matches in searched string.


1 Answers

According to Generate a Regular Expression to Match an Arbitrary Numeric Range, and after generating such a regex for your example at Regex_For_Range:

\b0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4])\b 

would do the trick.

The process would be (still following that Regex generator):

First, break into equal length ranges:

110 - 999 1000 - 2234 

Second, break into ranges that yield simple regexes:

110 - 199 200 - 999 1000 - 1999 2000 - 2199 2200 - 2229 2230 - 2234 

Turn each range into a regex:

1[1-9][0-9] [2-9][0-9]{2} 1[0-9]{3} 2[01][0-9]{2} 22[0-2][0-9] 223[0-4] 

Collapse adjacent powers of 10: 1[1-9][0-9] [2-9][0-9]{2} 1[0-9]{3} 2[01][0-9]{2} 22[0-2][0-9] 223[0-4]

Combining the regexes above yields:

0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4]) 

Next we'll try factoring out common prefixes using a tree:
Parse into tree based on regex prefixes:

. 1 [1-9] [0-9] + [0-9]{3} + [2-9] [0-9]{2} + 2 [01] [0-9]{2} + 2 [0-2] [0-9] + 3 [0-4] 

Turning the parse tree into a regex yields:

0*(1([1-9][0-9]|[0-9]{3})|[2-9][0-9]{2}|2([01][0-9]{2}|2([0-2][0-9]|3[0-4]))) 

We choose the shorter one as our result.

\b0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4])\b 
like image 153
VonC Avatar answered Oct 08 '22 07:10

VonC