\\[()] | [^()] ) | \g )* \) ) \x m=reg.match(str).to_a Wha...">
📜 ⬆️ ⬇️

Recursion in regular expressions

str = "a * ((bc)/(de) - f) * g"

reg = /(?
\(
(?:
(?>
\\[()]
|
[^()]
)
|
\g
)*
\)
)
\x

m=reg.match(str).to_a


What does this code do under the cut?

This code finds any nested expression with correctly placed parentheses.

reg = / (? # Begin naming expression
\ (# Open parenthesis
(?: # Uncommitted group
(?> # Comparison with own expression
\\ [()] # escaped bracket
| # OR
[^ ()] # no bracket at all
) # End of own expression
| # OR
\ g # Nested group in parentheses (recursive call)
) * * Unmemorable group
\) # Closing parenthesis
) # finite expressions
\ x #
')
m = reg.match (str) .to_a # [“a ((bc) / (de) - f)”. "a ((bc) / (de) - f)"]

We must not forget that left-sided recursion is prohibited.

What can be done.

str = "bbbaccc"
rel = /(? a|b\gc)/
re1.match(str).to_a


And so it is impossible.
re2 = /(? a|\gc)/

Source: https://habr.com/ru/post/50749/


All Articles