views:

105

answers:

2

Hi all, I need a regular expression that will match text enclosed in parentheses. The parentheses should be included. Here are some examples.

String: "(AB123-16W) DJ2988W61" Should match: "(AB123-16W)"

String: "(6541238 Rev. B, PS B1 & PS B2) 62MJ301-29 Rev. NC" Should match: "(6541238 Rev. B, PS B1 & PS B2)"

Any ideas?

+2  A: 
/(\(.*?\))/

Should match the items in parenthesis :D

You may not have to use the delimiters ( forward slashes ) in your language! Try with, and if that doesn't work, try without.

Mez
You might want a non-greedy version:(\(.*?\))since the greedy version with "Testing (123) Testing (123)" will match "(123) Testing (123)"
aquinas
Unfortunately that did not return any matches.
Tarzan
Upated wrt feedback.
Mez
@aquinas, your regular expression worked too. Thanks all for your help.
Tarzan
+1  A: 
var test1 = "(AB123-16W) DJ2988W61";
var test2 = "(6541238 Rev. B, PS B1 & PS B2) 62MJ301-29 Rev. NC";
var test3 = "(6541238 Rev. B, PS B1 & PS B2)(AB123-16W)";

Regex r = new Regex(@"(\([^)]*\))");

var result1 = (r.Matches(test1)[0].Groups[1].Value == "(AB123-16W)");
var result2 = (r.Matches(test2)[0].Groups[1].Value == "(6541238 Rev. B, PS B1 & PS B2)");
var result3 = (r.Matches(test3)[0].Groups[1].Value == "(6541238 Rev. B, PS B1 & PS B2)");
var result4 = (r.Matches(test3)[1].Groups[1].Value == "(AB123-16W)");

Debugger.Break();

All results variables will evaluate to true.

Gavin Miller
+1 for test cases.
m_oLogin