Regular expressions: Matching if number is greater

2020-03-31 02:15发布

I am in the need of an regexp that checks if one numerical value is greater then another value. Pretty much like I would by writing (if 10>8) ...

Clearly, my snippet won't make it happen and I lack the experience of regexp to sort it out by myself. Is this possible to do with regular expressions?

^[1-9]+[0-9]+$

Thanks!

标签: regex
4条回答
该账号已被封号
2楼-- · 2020-03-31 02:25

If I understand your problem correctly, you want a regex which matches two consecutive numbers of arbitrarily length where the second is greater than the first. This is not possible to do with regexen. It's clearly not a regular language and none of the common extensions (backreferences, recursive references) are powerful enough to change that.

In some regex implementations (e.g. perl's) it's possible to embed code in the host language into the regex. In that case you can of course just embed the predicate num1 < num2 as perl code, but I don't think that counts as a solution as a regex.

查看更多
贼婆χ
3楼-- · 2020-03-31 02:35

Well if I'm understand correctly you've to compare these number inside an .htaccess or something like that. There's a stupid and unhealty way to do the compare, and require the numbers in the evaluated string: "^[0-9] [1-9][0-9]$" match if you compare "5 12" so you can understand that 5 is less than 12.

Comparing number of same length isn't crazy only for numbers under 100.

I think If you can explain better which is your context (iMacros, .htaccess...) someone can suggest a better way to do this.

查看更多
▲ chillily
4楼-- · 2020-03-31 02:38

It is not something straightforwardly done with regular expressions. The language you are programming in may allow extensions to the regexp syntax to plug in arbitrary code. For example in Perl:

$_ = '54 55';
say 'matched' if /\A(\d\d) (\d\d)(?(?{$1 >= $2})(*FAIL))\z/;

This succeeds but 56 55 does not. In https://stackoverflow.com/a/30936388/626804 I explain a bit further.

Whether this is good taste or a good idea is another matter - but in Perl you can jam this kind of comparison into a so-called 'regular expression' match if you really want.

查看更多
做自己的国王
5楼-- · 2020-03-31 02:48

This is not a good problem for regexes to solve. Extract the numbers and compare them numerically.

查看更多
登录 后发表回答