[英]Regex - Match multiple times in a string
我正在嘗試對'NNTSY`進行正則表達式搜索,以便獲得兩次匹配。
當我嘗試使用模式?<NGrlyosylation>N[^P][ST][^P])"
匹配時,我只得到一個匹配,即NNTS
。
如何使用正則表達式來匹配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;
}
大多數編程語言(少數除外)通常不允許查找重疊的匹配項。 因此,我認為不存在一種解決此問題的純正則表達式方法,但是您可以在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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.