代码之家  ›  专栏  ›  技术社区  ›  jerjer

从字符串中检索所有可能与n个字符匹配的子字符串

  •  1
  • jerjer  · 技术社区  · 16 年前

    基本上,我想从一个字符串中检索所有可能的子字符串匹配项,这是我的初始代码,但它只返回2个匹配项。

    String input = "abc12345abcd";
    Regex  regex = new Regex(@"[A-Za-z]{3}"); //this will only return 2 matches
    MatchCollection  matches = regex.Matches(input);
    

    如何使用regex获取以下匹配项?

    abc
    abc
    bcd
    

    这有可能吗,如果不可能的话,Linq会帮上忙吗?

    2 回复  |  直到 16 年前
        1
  •  3
  •   YOU    16 年前
    String input = "abc12345abcd";
    Regex regex = new Regex(@"[A-Za-z]{3}");
    int i=0;
    while(i<input.Length){
        Match m=regex.Match(input,i);
        if(m.Success){
            Console.WriteLine(m.Value);
            i=m.Index+1; //just increment one char, instead of length of match string
        }else break;
    }
    

    结果

    abc
    abc
    bcd
    
        2
  •  2
  •   Alex Martelli    16 年前

    我相信,虽然没有明确的记录, Matches 收益率 不重叠 匹配——所以第二个匹配 abc 意味着没有退货 bcd 因为它会重叠。

    要获得重叠的匹配,可以编程一个循环,调用 Match (单数)一次获得一个匹配对象的方法;只要匹配对象具有 Success 属性为true,则继续循环使用 Match 方法比 Index 上一个匹配对象的属性(以获取下一个匹配,无论是否重叠)。