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

Regex - Match multiple times in a string

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

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

如何使用 Regex 匹配 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;
        }

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

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