正则表达式 - 在字符串中多次匹配

时间:2016-05-22 04:04:14

标签: c# regex rosalind

我正在尝试对'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 个答案:

答案 0 :(得分:2)

在大多数编程语言中通常不允许查找重叠匹配(少数编程语言除外)。 所以,我不认为存在一种纯正的正则表达式来解决这个问题,但你可以在C#中使用Substring lookahead作为

(?=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

相关问题