regex: get list of the locations of captured groups, not matches
Example string: #ABC ABC@ #ABC@ ABC
Example regex: /(?:[^#])(ABC)(?!@)/g
(only matches ABC
in the example)
I need to get a list of matches [[start,end],...] but not include the first group, which is only there because JS regex doesn't support lookbehind.
(Note: assume that the captured and uncaptured parts can be of any length, not just 1 or 3 characters like in the example)
Unfortunately, there is no way to get the indices where the groups matched inside the string.
As a workaround, make sure you capture the whole part of the pattern before the necessary capturing group/pattern part. Then, manipulate the match index and group legnth values as shown below:
var re = /([^#]|^)ABC(?!@)/g;
var str = 'ABC #ABC ABC@ #ABC@ ABC';
var pos = [];
while ((m = re.exec(str)) !== null) {
pos.push([m.index+m[1].length, m.index+m[0].length]);
}
console.log(pos);
链接地址: http://www.djcxy.com/p/12984.html
上一篇: 这个转发正则表达式示例如何工作?
下一篇: 正则表达式:获取捕获组的位置列表,不匹配