Regex to restrict only second occurrence of open and close brackets using C#
I have a string "开发者_如何学运维(BETA) (Feb 27, 2011)"
I need to get the second occurrence of the open and close brackets using C#
It is probably easiest to match all (...)
tokens and take the second:
MatchCollection matches = Regex.Matches(str, @"\(([^)]*)\)");
Getting the second match:
String second = matches[1].Groups[1].Value;
The regex assumes valid pairs of parentheses, and no nesting. It is pretty basic:
\(
- Opening.(...)
- Capturing group, to easily extract the value.[^)]*
- Content of the group - characters that are not(
.\)
- Closing.
Do you want it in regex? If not regex:
int n = text.indexOf("(");
if (n >= 0) {
n = text.indexOf("(", n+1);
}
Regex:
\(.+?\)\s*(\(.+?\))
Notice the use of a following "?" to force non-aggressive mode. And you must have at least one character within the parentheses.
精彩评论