Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find end index of a regular expression search/match

If I use string.match() with a regex, I'll get back the matched string, but not the index into the original string where the match occurs. If I do string.search(), I get the index, but I don't necessarily know how long the matched part of the string is. Is there a way to do both, so I can get the index of the end of the match in the original string?

I suppose I could do one after the other (below), assuming they return the same results but in a different way, but that seems ugly and inefficient, and I suspect there is a better way.

var str = "Fear leads to anger. Anger leads to hate. Hate leads to suffering"; 

var rgx = /l[aeiou]+d/i;
var match = str.match(rgx);
if (match && match[0]) {
  var i = str.search(rgx);
  console.log ("end of match is at index " + (i+match[0].length));
  }
like image 964
rob Avatar asked Mar 26 '11 06:03

rob


People also ask

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.

How do you end a regular expression?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.


1 Answers

.match returns a new array with the following properties:

The index property is set to the position of the matched substring within the complete string S.

The input property is set to S.

The length property is set to n +1.

The 0 property is set to the matched substring (i. e. the portion of S between offset i inclusive and offset e exclusive).

For each integer i such that i >0 and i <= n, set the property named ToString(i) to the ith element of r's captures array.

From http://bclary.com/2004/11/07/#a-15.10.6.2

match.index will provide what you need.

like image 157
HBP Avatar answered Sep 19 '22 12:09

HBP