如何在JavaScript正则表达式匹配中找到组的索引?
当我写一个正则表达式,如:如何在JavaScript正则表达式匹配中找到组的索引?
var m = /(s+).*?(l)[^l]*?(o+)/.exec("this is hello to you"); console.log(m); 
我得到第一个含有匹配对象以下内容:
{     0: "s is hello", 
    1: "s", 
    2: "l", 
    3: "o", 
    index: 3, 
    input: "this is hello to you" 
} 
我知道从index物业整场比赛的指标,但我也需要了解匹配组的开始和结束。使用简单的搜索将不起作用。在这个例子中,它会找到第一个“l”,而不是在组中找到的第一个。
有没有办法获得匹配组的偏移量?
回答:
您不能直接获取匹配组的索引。你所要做的是首先把每个字符在比赛组,即使你不关心的那些有关:
var m= /(s+)(.*?)(l)([^l]*?)(o+)/.exec('this is hello to you'); 现在你已经得到了全场比赛的部分:
['s is hello', 's', ' is hel', 'l', '', 'o'] function indexOfGroup(match, n) {     var ix= match.index; 
    for (var i= 1; i<n; i++) 
     ix+= match[i].length; 
    return ix; 
} 
console.log(indexOfGroup(m, 3)); // 11 
回答:
我写了一个简单的(以及初始化变得有点臃肿)JavaScript对象来解决:所以,你可以在你的组之前加起来字符串的长度,以获得从匹配索引到组索引偏移这个 我最近一直在研究一个项目的问题。它的工作方式与接受的答案相同,但会生成新的正则表达式并自动提取您请求的数据。
var exp = new MultiRegExp(/(firstBit\w+)this text is ignored(optionalBit)?/i); var value = exp.exec("firstbitWithMorethis text is ignored"); 
value = {0: {index: 0, text: 'firstbitWithMore'}, 
     1: null}; 
Git Repo:My MultiRegExp。希望这可以帮助那里的人。
编辑月,2015年:
我试试:MultiRegExp Live。
回答:
另一个JavaScript类,它也能解析嵌套组下可用:https://github.com/valorize/MultiRegExp2
用法:
let regex = /a(?:)bc(def(ghi)xyz)/g; let regex2 = new MultiRegExp2(regex); 
let matches = regex2.execForAllGroups('ababa bcdefghixyzXXXX')); 
Will output: 
[ { match: 'defghixyz', start: 8, end: 17 }, 
    { match: 'ghi', start: 11, end: 14 } ] 
回答:
基础上ecma regular expression syntax我写了一个解析器各自RegExp类的扩展除了这个问题(完全索引的exec方法)以及JavaScript RegExp实现的其他限制,例如解决此问题:基于组的搜索&替换。您可以test and download the implementation here(也可以用作NPM模块)。
实现原理如下(小例子):
//Retrieve content and position of: opening-, closing tags and body content for: non-nested html-tags. var pattern = '(<([^ >]+)[^>]*>)([^<]*)(<\\/\\2>)'; 
var str = '<html><code class="html plain">first</code><div class="content">second</div></html>'; 
var regex = new Regex(pattern, 'g'); 
var result = regex.exec(str); 
console.log(5 === result.length); 
console.log('<code class="html plain">first</code>'=== result[0]); 
console.log('<code class="html plain">'=== result[1]); 
console.log('first'=== result[3]); 
console.log('</code>'=== result[4]); 
console.log(5=== result.index.length); 
console.log(6=== result.index[0]); 
console.log(6=== result.index[1]); 
console.log(31=== result.index[3]); 
console.log(36=== result.index[4]); 
我试着以及从@velop执行,但执行似乎马车例如,它不能处理后向引用正确例如“/ a(?:)bc(def(\ 1 ghi)xyz)/ g” - 当在前面添加假名时,需要相应地增加反向引用\ 1,(这在他的实现中不是这样) 。
以上是 如何在JavaScript正则表达式匹配中找到组的索引? 的全部内容, 来源链接: utcz.com/qa/257195.html

