Home > Blockchain >  Why would you ever need (?(R)...|...) if condition in a regex?
Why would you ever need (?(R)...|...) if condition in a regex?

Time:12-01

I was looking though some regex documentation and was confused by something. The (R) condition in the context of (?(R)...|...) is said to be:

perl was a little cryptic:

(R)

    Checks if the expression has been evaluated inside of recursion. Full syntax: (?(R)then|else)

PCRE wasn't much use:

(?(R) overall recursion condition

and regular-expressions.info had nothing to say about it.

Is this condition to say if the subroutine stack is more than 1 level deep or does it mean something else?

CodePudding user response:

See this explanation:

if there is no subpattern named 'R', the condition is true if a recursive call to the whole pattern or any subpattern has been made

This implies that (?(R) condition checks if the whole pattern was recursed at least once, and the result of the check is boolean, either True if recursion took place, or False otherwise.

If you need to check some examples, see https://github.com/PhilipHazel/pcre2/blob/587b94277b50ababde2380b5877c93e36ca65db8/src/pcre2_jit_test.c.

  • Related