How can I put Regex.Matches into an array?

后端 未结 4 1770
花落未央
花落未央 2020-12-10 12:54

I have multiple Regex Matches. How can I put them into an array and call them each individually, for example ID[0] ID[1]?

string value = (\"{\\\         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 13:00

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

提交回复
热议问题