是否有一个函数返回RegEx匹配开始的索引?

时间:2009-12-05 10:19:33

标签: c# regex

我有15个字符长的字符串。我正在使用正则表达式对其执行一些模式匹配。我想知道IsMatch()函数返回true的子字符串的位置。

问题:是否有任何函数可以返回匹配的索引?

6 个答案:

答案 0 :(得分:40)

对于多个匹配,您可以使用与此类似的代码:

Regex rx = new Regex("as");
            foreach (Match match in rx.Matches("as as as as"))
            {
                int i = match.Index;
            }

答案 1 :(得分:10)

不使用IsMatch,而是使用Matches方法。这将返回MatchCollection,其中包含许多Match个对象。它们具有属性Index

答案 2 :(得分:10)

使用Match而不是IsMatch:

    Match match = Regex.Match("abcde", "c");
    if (match.Success)
    {
        int index = match.Index;
        Console.WriteLine("Index of match: " + index);
    }

输出:

Index of match: 2

答案 3 :(得分:4)

Regex.Match("abcd", "c").Index

2

注意#应检查Match.success的结果,因为它返回0,并且可能与位置0混淆,请参考Mark Byers Answer。感谢。

答案 4 :(得分:2)

使用IsMatch()

,而不是使用Matches
        const string stringToTest = "abcedfghijklghmnopqghrstuvwxyz";
        const string patternToMatch = "gh*";

        Regex regex = new Regex(patternToMatch, RegexOptions.Compiled);

        MatchCollection matches = regex.Matches(stringToTest); 

        foreach (Match match in matches )
        {
            Console.WriteLine(match.Index);
        }

答案 5 :(得分:-2)

Console.Writeline("Random String".IndexOf("om"));

这将输出4

a -1表示不匹配