PCRE has a feature called recursive pattern, which can be used to match nested subgroups. For example, consider the "grammar"
Q -> \\w | \'[\' A
The .Net alternative to recursive pattern is a stack. The challenge here is that we need to express the grammar it terms of stacks.
Here's one way of doing that:
A and Q in the question).This notation is somewhere between CFG and Pushdown automaton, where we push rules to the stack.
Let's start with a simple example: anbn. The usual grammar for this language is:
S -> aSb | ε
We can rephrase that to fit the notation:
# Start with
-> "a" | ε
-> "b"
In words:
S in the stack.S from the stack we can either:
B to the stack. This is a promise we will match "b". Next we also push S so we can keep matching "a"s if we want to.Bs from the stack, and match a "b" for each one.or, more loosely:
When we're in case S, match "a" and push B and then S, or match nothing.
When we're in case B, match "b".
In all cases, we pop the current state from the stack.
We need to represent the different states somehow. We can't pick '1' '2' '3' or 'a' 'b' 'c', because those may not be available in our input string - we can only match what is present in the string.
One option is to number our states (In the example above, S would state number 0, and B is state 1).
For state S