1

我正在尝试对“NNTSY”进行正则表达式搜索,以便获得两个匹配项。

  • NNTS
  • NTSY

当我尝试使用 pattern 进行匹配?<NGrlyosylation>N[^P][ST][^P])"时,我只得到一个匹配项,即NNTS.

如何使用 Regex 进行匹配NNTSY,以便找到两个匹配项?

注意:背景信息:可以在这里找到 Rosalind 问题。

这是我的代码。

        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;
        }
4

1 回答 1

2

大多数编程语言通常不允许查找重叠匹配(少数除外)。因此,我认为不存在解决此问题的纯正则表达式方法,但您可以Substring在 C# 中使用lookaheadas

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

于 2016-05-22T04:24:25.330 回答