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.


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:

| improve this answer | |
  • perl -lne 'print $& if /\( ( [^()]*+ | (?R) )* \)/gmx' file Very nice trick ! – Mévatlavé Kraspek 2 days ago

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

 ^^^^^^ ^^^^^^^^  ^^^^^^^ ^^^^^^ ^^^^^^^^
 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.
| improve this answer | |

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.