【问题标题】:How can I put Regex.Matches into an array?如何将 Regex.Matches 放入数组中?
【发布时间】:2011-01-08 04:59:40
【问题描述】:

我有多个正则表达式匹配。如何将它们放入一个数组并单独调用它们,例如ID[0] ID[1]

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\",");
string ID = Regex.Matches(textt, @value);`

【问题讨论】:

  • 上次我听说Matches() 返回了一个集合,而不是一个字符串。

标签: c# arrays regex


【解决方案1】:

您已经可以这样做了,因为 MatchCollection 有一个 int indexer 可以让您按索引访问匹配项。这是完全有效的:

MatchCollection matches = Regex.Matches(textt, @value);
Match firstMatch = matches[0];

但如果你真的想将匹配项放入一个数组中,你可以这样做:

Match[] matches = Regex.Matches(textt, @value)
                       .Cast<Match>()
                       .ToArray();

【讨论】:

  • 你可以为上面的第二个代码 sn-p 发布 vb 等效项吗?
  • @Smith Try: Dim matches() As Match = Regex.Matches(textt, @value).Cast(Of Match)().ToArray()
  • 我正在使用 .net 2.0,那里不支持这种转换
  • @ani 为什么我在 4.5 中没有演员表选项?
  • @EliEkstein 您需要导入使用 System.Linq :-)
【解决方案2】:

或者最后两个的组合可能更容易接受... MatchCollection 可以像数组一样直接使用 - 不需要辅助数组:

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\",");
MatchCollection matches = Regex.Matches(textt, @value);
for (int i = 0; i < matches.Count; i++)
{
    Response.Write(matches[i].ToString());
}

【讨论】:

    【解决方案3】:

    另一种方法

      string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\",");
      MatchCollection match = Regex.Matches(textt, @value);
    
      string[] ID = new string[match.Count];
      for (int i = 0; i < match.Length; i++)
      {
        ID[i] = match[i].Groups[1].Value; // (Index 1 is the first group)
      }
    

    【讨论】:

    • 二级阵列过于复杂。看我的回答。
    【解决方案4】:

    除了返回非强类型MatchCollection 的问题外,.NET 中的Regex.Matches() 方法还有一个问题。也就是说,尽管有一个重载允许您在输入字符串中指定起始索引,但无法限制字符数。

    以下扩展方法解决了这两个问题。它也比 Matches()MatchCollection.NET 配对简单得多,因为它消除了 MatchCollection 影响的惰性求值行为,而是一次返回完整的匹配集.

    public static Match[] Matches(this Regex rx, String s, int ix, int c)
    {
        if ((ix | c) < 0 || ix + c > s.Length)
            throw new ArgumentException();
    
        int i = 0;
        var rg = Array.Empty<Match>();
        Match m;
        while (c > 0 && (m = rx.Match(s, ix, c)).Success)
        {
            if (i == rg.Length)
                Array.Resize(ref rg, (i | 1) << 1);
    
            rg[i++] = m;
            c += ix - (ix = m.Index + m.Length);
        }
        if (i < rg.Length)
            Array.Resize(ref rg, i);
        return rg;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多