Recursion in regular expressions
str = "a * ((b-c)/(d-e) - f) * g"
reg = /(?
\(
(?:
(?>
\\[()]
|
[^()]
)
|
\g
)*
\)
)
\x
m=reg.match(str).to_a
What does this code do under cat.
This code finds any nested expression with correctly placed brackets.
reg = / (? # Beginning of a named expression
\ (# Opening parenthesis
(?: # Unrecorded group
(?> # Matching with own expression
\\ [()] # escaped bracket
| # OR
[^ ()] # not a bracket at all
) # End of proprietary expression
| # OR
\ g # Nested group in brackets (recursive call)
) * # Unrecorded group
\) # Closing parenthesis
) # end of expression
\ x #
m = reg.match (str) .to_a # ["a ((bc) / (de) - f). ” "a ((bc) / (de) - f)"]
We must not forget that left-handed retreat is prohibited.
What can be done. And it’s impossible.
str = "bbbaccc"
rel = /(? a|b\g c)/
re1.match(str).to_a
re2 = /(? a|\g c)/