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

1

5

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?

Acuminate answered 26/6, 2012 at 20:9 Comment(0)
O
13

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.

Onaonager answered 26/6, 2012 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.