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

标签 javascript html regex

我正在尝试使用 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/

相关文章:

regex - 对多个文件使用 pcregrep

javascript - 在加载时以编程方式调用页面顶部的 anchor 标记

regex - Firefox 错误 : Unable to check input because the pattern is not a valid regexp: invalid identity escape in regular expression

html - 为什么我的图标在 Font Awesome 上显示方 block ?

regex - 使用 bash 脚本从 header 中提取父 url

regex - 带反引号的 grep 正则表达式匹配所有行

javascript - 在一个事件中提交两个表单

javascript - 如何使用 isNaN 来检查输入是否为数字?

javascript - 这行代码是什么意思 obj.sayColor=sayColor

javascript - jQuery 动画有问题