Given a string like "4>2", and in general "X>Y" is there a way to create a regular expression that accepts the string iff the condition is true?
Asked
Active
Viewed 143 times
0
-
There probably is; some programming languages have Turing complete regex engines. – Matt Ball Jun 02 '13 at 05:18
-
4Horrifyingly, this has been asked before: http://stackoverflow.com/questions/298753/regex-compare-two-numbers http://stackoverflow.com/questions/5044104/regex-for-number-comparison?rq=1 http://stackoverflow.com/questions/10495267/regex-compare-number-with-constant?rq=1 – Charles Burns Jun 02 '13 at 05:21
-
Regular expressions are for matching patterns, not checking numeric values. Find a likely string with the regex, then check its numeric value in whatever your host language is (PHP, whatever). – Andy Lester Jun 02 '13 at 05:27
-
Working on an IOCCC (http://www.ioccc.org/) submission? – Sysyphus Jun 02 '13 at 05:36
-
What is the motivation here? If you are writing a program, it doesn't get any easier than splitting, parsing two numbers, and comparing them. But, maybe you are just trying to see if it is possible. – Kobi Jun 02 '13 at 05:51
2 Answers
3
You couldn't. As a counter example, you have to be able accept
10 > 1
and generally
10^n > 10^m
for n > m. This would require counting, which normal regular expressions can't do. That said, if you have much more powerful regular expressions, as some languages do, you might be able to do this.

Warwick Masson
- 883
- 7
- 17
-
3I'm pretty sure 99,9% of all [tag:regex] questions here on SO assume a modern Regex implementation and not the underpowered definition you learn in computer science 101. – ThiefMaster Jun 02 '13 at 07:42
0
You can, but it requires a few regexs (say for unsigned shorts 0 .. 65535), numbers not starting with a 0
Check on size, if
/^(\d{2}>\d{1})|(\d{3}>\d{2})|(\d{4}>\d{3})|(\d{5}>\d{4})$/
then ok, else check same length, if
/^(\d{1}>\d{1})|(\d{2}>\d{2})|(\d{3}>\d{3})|(\d{4}>\d{4})|(\d{5}>\d{5})$/
then (same length) check digit by digit, if
/^(9.*?>[1-8])|(8.*?>[1-7])|(7.*?>[1-6])|(6.*?>[1-5])|(5.*?>[1-4])|(4.*?>[1-3])|
(3.*?>[1-2])|(2.*?>1)/
else (2nd digit) if
/^(.9.*?>.[1-8])|(.8.*?>.[1-7])|(.7.*?>.[1-6])|(.6.*?>.[1-5])|(.5.*?>.[1-4])|(.4.*?>.[1-3])|
(.3.*?>.[1-2])|(.2.*?>.1)/
etc.. for 3rd to 5th digit

Déjà vu
- 28,223
- 6
- 72
- 100