简体   繁体   English

C#正则表达式匹配号后跟右括号

[英]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)". 我正在尝试匹配一个数字,并在其后加上一个右括号:“(2)”,但不匹配一个在左括号和右括号中的数字:“(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: 在表达式10)中匹配如下:

  • 1 is [^(] 1[^(]
  • 0) is \\d{1,}\\) 0)\\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; 等等: 1 )等等; and 2 ) blah blah. 2 )等等等等。 (1) Blah blah; (1)等等 and (10) blah blah.1 和(10)等等等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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