How to define recursion in Regular expression using recursive subexpression ?
Table of Contents
About
This page is about recursive subexpression in regular expression.
It permits to define string that shows a recursive pattern
Example
In Rugby syntax:
(?<S> (A \g<S> B)?)
where:
- ?<S> define the group name S for the expression enclosed in parenthesis. ie (A \g<S> B)?
- (A \g<S> B)? defines that the expression A \g<S> B should be found 0 or 1 (defined by the ? greedy quantifier)
- A \g<S> B defines a pattern that:
- starts with the letter A,
- followed by the group S (the recursion)
- then the letter B
Syntax
You define a recursive expression by adding the group name
- In PCRE (perl, php, java, …)
(?R)
- In Ruby
\g<0>
Support
Recursion is not supported in all regular expression engines. The following engines supports them
- PCRE (Perl, C, PHP, R…)
- Ruby (2+)
- Python with the alternate regex module