简体   繁体   中英

C# Regex Match Number Followed by Closing Parenthesis

I am trying to match a number followed by a closing parenthesis: "2)", but not match a number contained within opening and closing parentheses: "(2)". This regex works, except when the number has more than one digit:

string text = "blah blah: 1) blah blah; and 2) blah blah.  (1) Blah blah; and (10) blah blah.";
string pattern = @"[^(]\d{1,}\)";
MatchCollection matches = new Regex(pattern).Matches(text);
foreach (Match m in matches)
{
    Console.WriteLine(m);
}

// output:
// 1) 
// 2)
// 10)  This should not be matched, since it is really (10)

How can I modify this regex to match numbers that are followed by a closing parenthesis, but not preceded by an opening parenthesis?

实际上,您要匹配一个左括号,一个数字和一个右括号。

string pattern = @"[^(]\d+\)";

In your expression 10) is matched as follows:

  • 1 is [^(]
  • 0) is \\d{1,}\\)

Try with this one:

string pattern = @"[^(\d]\d+\)"

To avoid breaking the number.

Try

string pattern = @"(?<=\\s)\\d+(?=\\))"

and based on your input, it will match numbers (shown in bold)

blah blah: 1 ) blah blah; and 2 ) blah blah. (1) Blah blah; and (10) blah blah.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM