Home >Java >javaTutorial >Can Regex Match Nested Brackets Without Recursion or Balancing Groups?
Matching Nested Brackets Without Recursion or Balancing Groups
The Challenge:
Can regex expressions, such as those in Java's java.util.regex, match arbitrarily nested brackets without relying on recursion or balancing groups?
The Solution:
Yes, it is possible using forward references:
(?=\()(?:(?=.*?\((?!.*?)(.*\)(?!.*).*))(?=.*?\)(?!.*?)(.*)).)+?.*?(?=)[^(]*(?=$)
How It Works:
This expression consists of several lookaheads and forward references that work together to identify nested groups of parentheses:
Example:
The following string will match three nested groups:
(F(i(r(s)t))) ((S)(e)((c)(o))(n)d) (((((((Third)))))))
Matching Inner Groups:
To match inner groups, a capturing group can be added to the end of the expression:
(?=\()(?=((?:(?=.*?\((?!.*?)(.*\)(?!.*).*))(?=.*?\)(?!.*?)(.*)).)+?.*?(?=)[^(]*(?=$)))
The above is the detailed content of Can Regex Match Nested Brackets Without Recursion or Balancing Groups?. For more information, please follow other related articles on the PHP Chinese website!