Regular expressions: Matching if number is greater then…?

前端 未结 4 1431
灰色年华
灰色年华 2021-01-16 03:03

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) ...

Cl

相关标签:
4条回答
  • 2021-01-16 03:29

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

    0 讨论(0)
  • 2021-01-16 03:29

    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.

    0 讨论(0)
  • 2021-01-16 03:39

    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.

    0 讨论(0)
  • 2021-01-16 03:40

    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.

    0 讨论(0)
提交回复
热议问题