tags:

views:

89

answers:

6

I have strings of 15 characters long..i am performing some pattern matching on it with the use of regular expression. i want to know the position of string where the isMatch() function returns true.

Is there is any function that return index position of a string

I want to perform some operation on that index.

+3  A: 

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.

spender
+1  A: 

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
Mark Byers
+2  A: 
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.

S.Mark
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
Thx for pointing out.
S.Mark
+1  A: 

Fot multiple matches you can use something like this

Regex rx = new Regex("as");
            foreach (Match match in rx.Matches("as as as as"))
            {
                int i = match.Index;
            }
astander
A: 
Console.Writeline("Random String".IndexOf("om"));

This will output a 4

a -1 indicates no match

Paul Creasey
A: 

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