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

将正则表达式结果返回到数组

  •  0
  • Crash893  · 技术社区  · 16 年前

    我正在做一个小项目,这是我第一次使用正则表达式

    我试过使用。匹配或匹配。匹配,但我没有看到任何选项允许我将正则表达式查询的结果返回到数组。

    谢谢

    5 回复  |  直到 16 年前
        1
  •  2
  •   Petar Petrov    16 年前

    我还没有测试过,但类似的东西可以完成这项工作:

    public static IEnumerable<Match> GetMatches(Regex regex, string input)
    {
        var m = regex.Match(input);
        while (m.Success)
        {
            yield return m;
    
            m = m.NextMatch();
        }
    }
    
        2
  •  1
  •   AutomatedTester    16 年前

    如果你使用 Regex.Matches(input,regex,regexoptions) 它将返回一组匹配项,然后您可以遍历这些匹配项。

    收藏被认为是一种更好的开发工具( http://msdn.microsoft.com/en-us/library/k2604h5s(VS.71).aspx )

        3
  •  1
  •   Adriaan Stander    16 年前

    使用Matches CopyTo方法复制到您选择的数组。

    看看这个

    MatchCollection.CopyTo Method

    编辑评论

    像这样的

    Regex rg = new Regex("YourExpression");
    MatchCollection matcheCollection = rg.Matches("Your String");
    Match[] matches = new Match[matcheCollection.Count];
    matcheCollection.CopyTo(matches, 0);
    
        4
  •  1
  •   gingerbreadboy    16 年前
    Regex rg = new Regex("YourExpression");
    
    Match[] result = rg.Matches("Your String").OfType<Match>().ToArray();
    

    这样你就不用分门别类地定义匹配了。

        5
  •  1
  •   Ja77aman    14 年前

    要以字符串数组的形式返回正则表达式的匹配项,可以这样做。

        string[] stringArray; // this this will become our String array,
    
        Regex regex = new Regex(@"<your regex goes here>");
        List <String> listTemp = new List<string>();
        foreach (Match matchItem in regex.Matches(<your string to spit/match>))
        {
           listTemp.Add(matchItem.ToString());
        }
        stringArray = listTemp.ToArray<String>();
    

    希望这有帮助!