Node/Javascript 中的 RegEx - 如何获得模式匹配边界?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11215184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx in Node/Javascript - how to get pattern match bounds?
提问by ControlAltDel
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?
目前,我通过 find() 在 Javascript / Node 中使用正则表达式,它用于查找模式的开头。但我也希望能够找出模式的结束位置。那可能吗?
回答by Markus Jarderot
If you use the RegExp.exec()
method, you can get the information you need.
如果使用该RegExp.exec()
方法,则可以获得所需的信息。
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.
/\d+\.?\d*|\.\d+/
相当于new RegExp("\\d+\\.?|\\.\\d+")
。文字语法节省了一些反斜杠。