Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

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?

like image 378
Royson Avatar asked Dec 05 '09 10:12

Royson


People also ask

Which method returns the first index where a regular expression is found?

The Match(String) method returns the first substring that matches a regular expression pattern in an input string.

Can you use regex to index?

We can use the JavaScript regex's exec method to find the index of a regex match. For instance, we can write: const match = /bar/. exec("foobar"); console.

What is the use of SPAN () in regular expression?

span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1). Parameters: group (optional) By default this is 0. Return: A tuple containing starting and ending index of the matched string.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

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; } 
like image 156
Adriaan Stander Avatar answered Oct 11 '22 20:10

Adriaan Stander


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 
like image 42
Mark Byers Avatar answered Oct 11 '22 19:10

Mark Byers