Insert Regular Expression RecursionThe Insert Token button on the Create panel makes it easy to insert tokens that recurse the whole regular expression. Only a few regex engines such as Perl, PCRE, and Ruby support this.
With (?R) or \g<0> you can make your regular expression recurse into itself. The Recursion item in the Insert Token menu automatically selects the correct syntax for your application.
You’ll need to make sure that your regular expression does not recurse infinitely. The recursion token must not be the first token in the regex. The regex must match at least one character before the next recursion, so that it will actually advance through the string. The regex also needs at least one alternative that does not recurse, or the recursion itself must be optional, to allow the recursion to stop at some point.
Recursion is mostly used to match balanced constructs. The regex \([^()]*+(?:(?R)[^()]*+)*+\) matches a pair of parentheses with all parentheses between them correctly nested, regardless of how many nested pairs there are or how deeply they are nested. This regex satisfies both requirements for valid recursion. The recursion token is preceded by \( which matches sure that at least one character (an opening parenthesis) is matched before the next recursion is attempted. The recursion is also optional because it is inside a group that is made optional with the quantifier *+.
If recursion behaves differently in your application depending on the syntax you use then the Recursion menu item shows a dialog box that lets you select how you want the recursion to handle backtracking and capturing groups. In the Just Great Software applications, recursion behaves the way it originally did in Perl, PCRE, and Ruby, depending on whether you use the syntax introduced by Perl, PCRE, or Ruby.
If recursion always behaves the same in your application the Recursion menu item inserts the syntax supported by the application directly. The Create panel explains the exact behavior if you set it to Detailed or Precise mode. Do pay attention to this. It differs not only between Perl, PCRE, and Ruby, but also between different versions of Perl and different versions of PCRE2.
The differences don’t affect the example on this page. The regex uses only possessive quantifiers, which never backtrack, and it doesn’t have any capturing groups.
