2016-02-25 182 views
0

我想匹配一个数字后跟一个右括号:“2)”,但不匹配打开和关闭圆括号内包含的数字:“(2)”。此正则表达式的作品,除了当数已超过一个数字:C#正则表达式匹配号码后跟关闭括号

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) 

如何修改这个正则表达式来匹配后跟一个右括号,而不是由一个左括号前面的数字?

回答

1

在您的表达10)匹配如下:

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

尝试用这一个:

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

为了避免损坏的数量。

+0

这样做!我现在觉得有点笨...... –

+0

别担心 –

1

实际上,您想匹配左括号,数字和右括号。

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

尝试

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

,并根据您的输入,它会匹配数字(以粗体显示)

等等等等:)等等等等;和)等等等等。 (1)Blah等等;和(10)等等等等。