开发者

How can I put Regex.Matches into an array?

I have multiple Regex Matches. How can I put them into an array and call them each individ开发者_运维问答ually, for example ID[0] ID[1]?

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


You can do that already, since MatchCollection has an int indexer that lets you access matches by index. This is perfectly valid:

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

But if you really want to put the matches into an array, you can do:

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


Or this combo of the last 2 might be a little easier to take in... A MatchCollection can be used like an array directly - no need for the secondary array:

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());
}


another method

  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)
  }


Besides the problem of returning a non-strongly-typed MatchCollection, there's an additional problem with the Regex.Matches() method in .NET. Namely, although there's an overload that lets you specify a starting index in the input string, there's no way to limit the character count.

The following extension method solves both problems. It's also considerably simpler than the .NET pairing of Matches() and MatchCollection because it does away with the lazy-evaluation behavior effected by MatchCollection, instead returning the complete set of matches all at once.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜