簡體   English   中英

正則表達式與C#中的交集匹配

[英]regex matches with intersection in C#

我想知道是否有可能獲得所有匹配的MatchCollection,即使它們之間存在交集。

string input = "a a a";
Regex regex = new Regex("a a");
MatchCollection matches = regex.Matches(input);
Console.WriteLine(matches.Count);

此代碼返回1,但我希望它返回2.如何實現它?
謝謝您的幫助。

string input = "a a a";
Regex regexObj = new Regex("a a");
Match matchObj = regexObj.Match(input);
while (matchObj.Success) {
    matchObj = regexObj.Match(input, matchObj.Index + 1); 
}

將迭代字符串,開始下一次迭代,在前一個匹配位置之后的一個字符,因此找到所有匹配。

您可以在while循環中將“aa”替換為“a”並將其與正則表達式再次匹配,直到沒有匹配為止。

暫無
暫無

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

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