简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM