How to define recursion in Regular expression using recursive subexpression ?


This page is about recursive subexpression in regular expression.

It permits to define string that shows a recursive pattern


In Rugby syntax:

(?<S> (A \g<S> B)?)


  • ?<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


You define a recursive expression by adding the group name

  • In PCRE (perl, php, java, …)
  • In Ruby


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

Powered by ComboStrap