Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple regex to compare numbers to x?

Tags:

regex

I want a regex that will match if a number is greater than or equal to an arbitrary number. This seems monstrously complex for such a simple task... it seems like you need to reinvent 'counting' in an explicit regex hand-crafted for the x.

For example, intuitively to do this for numbers greater than 25, I get

(\d{3,}|[3-9]\d|2[6-9]\d)

What if the number was 512345? Is there a simpler way?

like image 556
Cory Kendall Avatar asked Dec 17 '22 05:12

Cory Kendall


2 Answers

Seems that there is no simpler way. regex is not thing that for numbers.
You may try this one:

\[1-9]d{6,}|
[6-9]\d{5}|
5[2-9]\d{4}|
51[3-9]\d{3}|
512[4-9]\d{2}|
5123[5-9]\d|
51234[6-9]

(newlines for clarity)

like image 178
RiaD Avatar answered Jan 13 '23 16:01

RiaD


What if the number was 512345? Is there a simpler way?

No, a regex to match a number in a certain range will be a horrible looking thing (especially large numbers ranges).

Regex is simply not meant for such tasks. The better solution would be to "freely" match the digits, like \d+, and then compare them with the language's relational operators (<, >, ...).

like image 42
Bart Kiers Avatar answered Jan 13 '23 15:01

Bart Kiers