2016-05-22 150 views
1

我想在'NNTSY`上做一個正則表達式搜索,這樣我就可以得到兩個匹配。正則表達式 - 在一個字符串中多次匹配

  • NNTS
  • NTSY

當我試圖使用模式?<NGrlyosylation>N[^P][ST][^P])"匹配,我只得到一個匹配,這是NNTS

如何使用正則表達式匹配NNTSY以便找到兩個匹配項?

注意:背景信息:Rosalind問題可以找到here

這是我的代碼。

 input = "NNTSY"; 
     Regex regex = new Regex("(?<NGrlyosylation>N[^P][ST][^P])", RegexOptions.Compiled | RegexOptions.IgnoreCase); 
     MatchCollection matches = regex.Matches(input); 
     foreach (Match match in matches) 
     { 
      // Need to add 1 to because match index is 0 based 
      const int offset = 1; 
      yield return match.Index + offset; 
     } 
+1

你正試圖找到重疊匹配 – rock321987

+0

@ rock321987是的。究竟。 – Sung

+0

對於那些想要完整源代碼的人,請查看這裏的源代碼=> https://github.com/dance2die/Demo.Rosalind/blob/master/Demo.Rosalind/Demo.Rosalind.Tests/MPRT/MprtTest.cs – Sung

回答

2

尋找重疊比賽通常在大多數編程語言允許(少數除外)。 所以,我不認爲存在解決這個純粹的正則表達式的方法,但你可以在C#中使用Substringlookahead

(?=N[^P][ST][^P]). 

C#代碼

string input = "NNTSY"; 
Regex regex = new Regex("(?=N[^P][ST][^P]).", RegexOptions.Compiled | RegexOptions.IgnoreCase); 

Match match = regex.Match(input); 

while (match.Success) 
{ 
    Console.WriteLine(input.Substring(match.Index, 4)); 
    match = match.NextMatch(); 
} 

Ideone Demo

+0

謝謝@ rock321987。我不知道正則表達式的概念,所以我迷路了。至少我創建的測試通過了所有的情況,我準備繼續前進。 – Sung

+0

@Sung很高興,它幫助..'lookaheads'是零寬度assertion ..這意味着他們不會消耗任何字符..正則表達式將被檢查對字符串沒有消耗匹配的字符串 – rock321987

+0

@Sung'.'在正則表達式中是不需要的。簡單的lookahead在這裏就足夠了。加入'''會加快處理速度 – rock321987