Can I use a backlink in a range of numbers?

I want to match a string where the number is equal to or greater than the number in the capture group.

Example:

  • 1x1 = match
  • 1x2 = match
  • 2x1 = no match

In my view, the regex would look something like this: (\d)x[\1-9] , but that doesn't work. Is it possible to achieve this with regex?

+5
source share
1 answer

As you have discovered, you cannot interpolate a value in a regular expression because:

Since character classes are defined when compiling a regular expression ... The only type of character in the node class is the "hard-coded list of characters" that was created when compiling the regular expression (not after it was partially executed and found out that it could cost $ 1.)

[ Source ]

Since character classes do not allow backreferences, a backslash followed by a number is renamed to a character class:

A backslash followed by two or three octal digits is considered an octal number.

[ Source ]

This is clearly not what you intended [\1-9] . But since there is no way to compile a character class until all characters are known, we have to find another way.

If we want to do this completely in regular expression, we cannot list all the possible combinations, because we will need to check all the captures to find out which one matches. For example :

 "1x2" =~ m/(?:(0)x(\d)|(1)x([1-9])|(2)x([2-9])|(3)x([3-9])|(4)x([4-9])|(5)x([5-9])|(6)x([6-9])|(7)x([7-9])|(8)x([89])|(9)x(9))/ 

It will contain “1” at $3 and “2” at $4 , but you will have to search from 1 to 20 to find if something has been agreed upon each time.


The only way to post-process the results of regular expressions is to use a conditional expression: (?(A)X) Where A is conditional and X is the result of the action.

Unfortunately, conditional expressions are not supported by RE2 , but we will continue to demonstrate that this can be done.

What you would like to use for X is (*F) (or (?!) In Ruby 2+) to force a crash: http://www.rexegg.com/regex-tricks.html#fail

What you would like to use for A is ?{$1 > $2} , but only Perl will allow you to use the code directly in the regular expression . Perl will allow you to use:

 m/(\d)x(\d)(?(?{$1 > $2})(?!))/ 

[ Live Example ]

So, the answer to your question is: “ No, you cannot do this with RE2, which uses Google Analytics , but yes, you can do it with a Perl regular expression.”

+2
source

Source: https://habr.com/ru/post/1243747/


All Articles