使用RegExp在模式中查找多个模式实例

问题描述:

我试图使用RegExp查找多个文本匹配,所有这些匹配都显示在模式中。 例如: 假设我有一个div标签包含一个“文本阵”:使用RegExp在模式中查找多个模式实例

<div class="example" data-uris="[a][b][c]" data-title=".../> 

我试图做使用正则表达式,就是找3组:A,B和C。 所有这些当然都遵循特定的div,并且会察觉到引号和其他属性,这些属性在字符串中只显示一次,并且每个组都重复包含在方括号内。 但是,构建正则表达式只会提供第一组:a。

任何想法?

+2

提供输入和预期输出 – Sachin

+0

我做到了。考虑我的给定div。 为此,我想找到a,b和c(它们可能比单个字符更长,但这个例子会很好) –

+0

使用jquery还是只有js? – Sachin

这里是正则表达式exec方法扩展的解决方案:

<div class="example" data-uris="[abc][bde][cfg]" data-title=""></div> 

var div = document.getElementsByClassName('example')[0], 
    uris = div.getAttribute('data-uris'), 
    match, 
    matches = [], 
    pattern = /\[([a-z]+)+?\]+/g; 

while((match = pattern.exec(uris)) != null){ 
    matches.push(match[1]); 
} 
console.log(matches); 
// output: Array [ "abc", "bde", "cfg" ] 

的代码片段:

var div = document.getElementsByClassName('example')[0], 
 
    uris = div.getAttribute('data-uris'), 
 
    match, 
 
    matches = [], 
 
    pattern = /\[([a-z]+)+?\]+/g; 
 
    
 
while((match = pattern.exec(uris)) != null){ 
 
    matches.push(match[1]); 
 
} 
 
console.log(matches);
<div class="example" data-uris="[abc][bde][cfg]" data-title=""></div>

+0

我需要使用一个RegEx,但不能修改/添加代码, 因此我可以确保div及其属性,然后在 –

+0

@ShlomiUziel中获得几个括号内的匹配项,如果将会有50个带有“example”类的div。 ?应该选择哪一个?看起来你会“发明”一些冗余的逻辑,这可能比较简单。 – RomanPerekhrest

+0

然后我想要它们全部 –

如果我理解正确的问题,这可能是你的开始e寻找:

// iteration through elements 
var elements = window.document.all; 
for (var i = 0, l = elements.length; i < l; i++) { 
    if (elements[i].localName === 'div') { 
     console.log(elements[i].outerHTML.match(/\[a\]\[b\]\[c\]/)); 
    } 
} 
// match on the document's text 
var html = window.document.documentElement.innerHTML; 
console.log(html.match(/\[a\]\[b\]\[c\]/)); 
+0

我需要在完整的HTML文本上应用正则表达式,而不应用任何其他方法(即,不使用代码遍历DOM元素树) –

+0

您可以通过'window.document.documentElement.innerHTML' ,我会举个例子。 –

+0

很好奇,这是否帮助你实现你正在尝试做的@ShlomiUziel? –