簡體   English   中英

C#正則表達式匹配號后跟右括號

[英]C# Regex Match Number Followed by Closing Parenthesis

我正在嘗試匹配一個數字,並在其后加上一個右括號:“(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)

如何修改此正則表達式以匹配后跟右括號但不跟右括號的數字?

實際上,您要匹配一個左括號,一個數字和一個右括號。

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

在表達式10)中匹配如下:

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

試試這個:

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

為了避免打破數字。

嘗試

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

並根據您的輸入匹配數字(以粗體顯示)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM