Patterns that match themselves
Recursion lets a pattern reference itself. The classic use: matching balanced brackets to arbitrary depth, which pure regex (a regular language) can't do. With recursion, regex extends into context-free grammar territory.
Syntax
(?R)— recurse the entire pattern(?N)— recurse group N(?P>name)or(?&name)— recurse named group
Balanced brackets example
\((?:[^()]++|(?R))*\)
Reading: an opening paren, then any number of (non-paren chars OR a recursive paren-pair), then a closing paren. The (?R) recurses the whole pattern, so it matches nested pairs of any depth.
Engine support
- PCRE, PHP, Perl: Yes
- Python
regexthird-party: Yes - Python
re: No - JavaScript, .NET, Ruby, Java, Go: No
Recursion is one of the least-portable features. If you need it, you're either committed to PCRE OR you should use a real parser.
The rule of thumb
If you're reaching for recursive regex, the problem is probably parsing. Real parsers handle balanced delimiters cleanly without exotic regex features. Use Python ast for code, json for JSON, html.parser for HTML, even hand-written tokenizers for custom DSLs. Recursive regex exists; using it usually means you should have switched tools.