开发者

Is there a function that returns index where RegEx match starts?

开发者 https://www.devze.com 2022-12-13 03:17 出处:网络
I have strings of 15 characters long. I am performing some pattern matching on it with a regular expression. I want to know the position of the substring where the IsMatch() function r开发者_JAVA技巧e

I have strings of 15 characters long. I am performing some pattern matching on it with a regular expression. I want to know the position of the substring where the IsMatch() function r开发者_JAVA技巧eturns true.

Question: Is there is any function that returns the index of the match?


For multiple matches you can use code similar to this:

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


Use Match instead of IsMatch:

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

Output:

Index of match: 2


Instead of using IsMatch, use the Matches method. This will return a MatchCollection, which contains a number of Match objects. These have a property Index.


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

2

Note# Should check the result of Match.success, because its return 0, and can confuse with Position 0, Please refer to Mark Byers Answer. Thanks.


Rather than use IsMatch(), use 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);
        }


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

This will output a 4

a -1 indicates no match

0

精彩评论

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