我正在尝试使用 RegExp 查找多个文本匹配项,所有这些文本匹配项都显示在一个模式中。 例如: 假设我有一个包含“文本数组”的 div 标签:
<div class="example" data-uris="[a][b][c]" data-title=".../>
我试图使用正则表达式来找到 3 个组:a、b 和 c。 当然,所有这些都遵循某个 div,并引用引号和其他属性,这些属性在字符串中仅出现一次,并且每个组都重复包含在方括号内。 但是,构建正则表达式将仅提供第一组:a.
有什么想法吗?
最佳答案
这是使用 regexp 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>
关于javascript - 使用 RegExp 在模式中查找模式的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932650/