Regular expression to match balanced parentheses
regex
Solution
Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.
But there is a simple algorithm to do this, which I described in more detail in this answer to a previous question. The gist is to write code which scans through the string keeping a counter of the open parentheses which have not yet been matched by a closing parenthesis. When that counter returns to zero, then you know you've reached the final closing parenthesis.
Problem
I need a regular expression to select all the text between two outer brackets. Example: `START_TEXT(text here(possible text)text(possible text(more text)))END_TXT` ` ^ ^ ` Result: `(text here(possible text)text(possible text(more text)))`
Related problems
- What are regular expression Balancing Groups?
- Reference - What does this regex mean?
- Recursive pattern in regex
- Is it possible to match nested brackets with a regex without using recursion or balancing groups?
- Regular expression to detect semi-colon terminated C++ for & while loops
- Using RegEx to balance match parenthesis
- How to match string within parentheses (nested) in Java?
- Why is {a^nb^n | n >= 0} not regular?