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?
The Match(String) method returns the first substring that matches a regular expression pattern in an input string.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With