Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx in Node/Javascript - how to get pattern match bounds?

Currently, I'm using regex in Javascript / Node via find() and that works for finding the beginning of the pattern. But I'd also like to be able to find out where the pattern ends. Is that possible?

like image 981
ControlAltDel Avatar asked Jun 26 '12 20:06

ControlAltDel


People also ask

How do I return all matches in regex?

str. match(pattern) , if pattern has the global flag g , will return all the matches as an array.

What is ?: In regex?

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.

What are regex flags?

A flag is an optional parameter to a regex that modifies its behavior of searching. A flag changes the default searching behavior of a regular expression. It makes a regex search in a different way. A flag is denoted using a single lowercase alphabetic character.


1 Answers

If you use the RegExp.exec() method, you can get the information you need.

var pattern = /\d+\.?\d*|\.\d+/;
var match = pattern.exec("the number is 7.5!");

var start = match.index;
var text = match[0];
var end = start + text.length;

/\d+\.?\d*|\.\d+/ is equivalent to new RegExp("\\d+\\.?|\\.\\d+"). The literal syntax saves some backslashes.

like image 72
Markus Jarderot Avatar answered Oct 03 '22 16:10

Markus Jarderot