R

TestRegex

← Back to Blog

Impossible Regex: Recursive Patterns in PCRE

Computer Science 101 teaches us that Regular Expressions cannot parse Context-Free Grammars (like nested brackets). However, the PCRE (PHP, Perl, Python re) engine cheats.

Recursion (?R)

PCRE allows a pattern to call itself explicitly. This enables matching balanced sets of parentheses.

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

Explanation

Match an opening bracket \(. Then, match either non-bracket characters [^()] OR recurse the entire pattern (?R). Repeat until specific closing bracket.

Note: This is not supported in native JavaScript regex!