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

本文关键字:正则表达式 编号 | 更新日期: 2023-09-27 18:36:24

我正在尝试匹配一个数字,后跟一个右括号:"2)",但不匹配左括号和右括号中包含的数字:"(2)"。 此正则表达式有效,除非数字有多个数字:

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)

如何修改此正则表达式以匹配后跟右括号但前面没有左括号的数字?

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

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

  • 1 表示[^(]
  • 0) 'd{1,}')

试试这个:

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

以避免打破数字。

实际上,您希望匹配左括号、数字和右括号。

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

尝试

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

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

等等

1)等等;2)等等等等。 (1)胡说八道;(10)等等。