如何使用正则表达式获取所有匹配项

时间:2013-09-17 07:35:13

标签: c# .net regex

我需要使用正则表达式(即所有组合)获得给定单词中的所有匹配

内容:

  

ABC

从此我需要得到AB和BC,当我给出一些像[A-Z] [A-Z]的模式。 现在它只给出“AB”作为匹配模式。

提前致谢

4 个答案:

答案 0 :(得分:2)

int i = 0;
List<Match> matches = new List<Match>();
while(i < input.Length){
  Match m = Regex.Match(input.Substring(i),"[A-Z]{2}");
  if(m.Success){
    matches.Add(m);
    i += m.Index+1;
  }else break;
}

你也可以实现它以支持lazy匹配,如下所示:

public static IEnumerable<Match> Matches(string input, string pattern) {
        int i = 0;
        while (i < input.Length){
            Match m = Regex.Match(input.Substring(i), "[A-Z]{2}");
            if (m.Success) {
                yield return m;
                i += m.Index + 1;
            }
            else yield break;
        }
}
//Use it
var matches = Matches(input, "[A-Z]{2}");

答案 1 :(得分:1)

您可以使用前瞻,这样您就不会使用匹配项:

(?=([A-Z]{2}))

ideone demo

答案 2 :(得分:1)

.NET支持外观中的捕获组

var result=Regex.Matches(input,"(?=(..))")
                .Cast<Match>()
                .Select(x=>x.Groups[1].Value);

答案 3 :(得分:-2)

int i = 0;
List<Match> matches = new List<Match>();
while(i < input.Length){
  Match m = Regex.Match(input,"[A-Z][Z-A]");
  if(m.Success){
    matches.Add(i++);
    i = m.Index ++ 1;
  }
}
相关问题