I am trying to create a .NET RegEx expression that will properly balance out my parenthesis. I have the following RegEx expression:
func([a-zA-Z_][a-zA-Z0-9_]*)\(.*\)
The string I am trying to match is this:
"test -> funcPow((3),2) * (9+1)"
What should happen is Regex should match everything from funcPow until the second closing parenthesis. It should stop after the second closing parenthesis. Instead, it is matching all the way to the very last closing parenthesis. RegEx is returning this:
"funcPow((3),2) * (9+1)"
It should return this:
"funcPow((3),2)"
Any help on this would be appreciated.
Regular Expressions can definitely do balanced parentheses matching. It can be tricky, and requires a couple of the more advanced Regex features, but it’s not too hard.
Example:
Balanced matching groups have a couple of features, but for this example, we’re only using the capture deleting feature. The line
(?<-open> \) )will match a)and delete the previous “open” capture.The trickiest line is
(?(open)(?!)), so let me explain it.(?(open)is a conditional expression that only matches if there is an “open” capture.(?!)is a negative expression that always fails. Therefore,(?(open)(?!))says “if there is an open capture, then fail”.Microsoft’s documentation was pretty helpful too.