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.

2 Answers2

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.
AlexP
  • 10,217
  • 32
  • 41
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: