开发者

Regex to restrict only second occurrence of open and close brackets using C#

开发者 https://www.devze.com 2023-02-18 18:34 出处:网络
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 sec

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消