Regular Expressions Subpattern definitions


Example

The (?(DEFINE)...) construct lets you define subpatterns you may reference later through recursion. When encountered in the pattern it will not be matched against.

This group should contain named subpattern definitions, which will be accessible only through recursion. You can define grammars this way:

(?x) # ignore pattern whitespace
(?(DEFINE)
  (?<string> ".*?" )
  (?<number> \d+ )
  (?<value>
    \s* (?:
        (?&string)
      | (?&number)
      | (?&list)
    ) \s*
  )
  (?<list> \[ (?&value) (?: , (?&value) )* \] )
)
^(?&value)$

This pattern will validate text like the following:

[42, "abc", ["foo", "bar"], 10]

Note how a list can contain one or more values, and a value can itself be a list.