Royson
Royson

Reputation: 2901

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

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 returns true.

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

Upvotes: 41

Views: 55052

Answers (6)

YOU
YOU

Reputation: 123841

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.

Upvotes: 7

Adriaan Stander
Adriaan Stander

Reputation: 166406

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

Upvotes: 56

Mitch Wheat
Mitch Wheat

Reputation: 300559

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

Upvotes: 4

Paul Creasey
Paul Creasey

Reputation: 28834

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

This will output a 4

a -1 indicates no match

Upvotes: -3

Mark Byers
Mark Byers

Reputation: 838286

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

Upvotes: 29

spender
spender

Reputation: 120470

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.

Upvotes: 15

Related Questions