Question

I'm trying to process the text from a string with lots of parentheses, so I thought I'd use a regular expression to do it.

I've been searching and found a good solution over here :

Finding All Characters Between Parentheses with a .NET Regex

And adapted it to my code like this :

\(([^(]+)\)

When trying code this :

string s = "(hey (brother)) and (hey sister)";
string p = "\\(([^(]+)\\)";
Match m = Regex.Match(s, p);
Console.Write(m.Value+"\n");

I get the following result :

(brother))

I wanted to expression to stop when finding the first ")" and it's not doing so. Can anyone help me with a solution?

Was it helpful?

Solution

Your regex is trying to match as many characters as it can before it stops at a ) character. There are three ) characters in your string, but starting at b the regex cannot match the third ) because there is a ( between b and the third ), and the ( doesn't fit the pattern between the [ ] brackets. But your regex can (and does) use the second ) to match the ) in its pattern.

Note that on the page you linked to, the answer from which you got this regexp specifically says it will not work when the parentheses are nested inside each other.

You can force the regexp to match the first ) rather than the second if you write the regexp so:

\(([^()]+)\)

OTHER TIPS

You need to also exclude the end paren character if you want to stop when you get to one:

\(([^()]+)\)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top