37

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?

2
  • Do you mean the index of a match in the string or the index of a matching string in a collection?
    – H H
    Dec 5, 2009 at 10:35
  • index of match in the string...
    – Royson
    Dec 5, 2009 at 10:37

6 Answers 6

53

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

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
11

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.

6
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.

1
  • Note that this returns 0 if the regex does not match, which is probably not what you want. You should check match.Success first (see my answer).
    – Mark Byers
    Dec 5, 2009 at 10:26
2

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);
        }
-3
Console.Writeline("Random String".IndexOf("om"));

This will output a 4

a -1 indicates no match

1
  • 4
    Question asks about "pattern matching with a regular expression". IndexOf doesn't support patterns, only simple strings.
    – Ben Voigt
    Dec 21, 2014 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.