Regex with recursive expression to match nested braces?
perl, recursion, regex
Solution
There are numerous problems. The recursive bit should be:
(
(?: \{ (?-1) \}
| [^{}]+
)*
)
All together:
my $regex = qr/
sp\s+
\{
(
(?: \{ (?-1) \}
| [^{}]++
)*
)
\}
/x;
print "$1\n" if 'sp { { word } }' =~ /($regex)/;
Problem
I'm trying to match text like `sp { ...{...}... }`, where the curly braces are allowed to nest. This is what I have so far: ``` my $regex = qr/ ( #save $1 sp\s+ #start Soar production ( #save $2 \{ #opening brace [^{}]* #anything but braces \} #closing brace | (?1) #or nested braces )+ #0 or more ) /x; ``` I just cannot get it to match the following text: `sp { { word } }`. Can anyone see what is wrong with my regex?