1

Is anyone here can explain a case where the recursive Perl/PCRE regex (?R) can be helpful ?

I read

but still can't find a use-case.

0

2 Answers 2

2

The canonical example is matching an arithmetical expression containing numbers, operators and subexpressions in parentheses:

([0-9]+|\((?R)\))([-+*\/]([0-9]+|\((?R)\)))*
 ^^^^^^ ^^^^^^^^  ^^^^^^^ ^^^^^^ ^^^^^^^^
 number (subexp)   oper   number (subexp)
\______  _______/        \______  _______/
       \/                       \/
  One of those             One of those
                  \__________  ____________/
                             \/
                     Zero or more of those

that is, match

  • Either a number or a subexpression in parentheses, followed by
  • Zero or more times an operator and either a number or a subexpression in parentheses.
1

That is the tool to use to match nested structures, like nested parenthesis.
The mathematical defined regular expressions can not match this.

\(  ( [^()]*+ | (?R) )*  \)

View it online (spaces should be ignored).

Please read:

1
  • perl -lne 'print $& if /\( ( [^()]*+ | (?R) )* \)/gmx' file Very nice trick ! Jul 1, 2020 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.