好的,我想我需要重新发布我最初的问题:
Javascript Regex group multiple
有一个完整的例子。我有:
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/m;
var match = regex.exec( text );
console.log(match)
console.log 的输出是:
问题是我只得到第一个结果...... 不是另一个……我该怎么做才能捕获并遍历所有匹配的东西?
最佳答案
exec
一次只返回一个结果,并将指针设置为该匹配的末尾。因此,如果您想获得所有匹配项,请使用 while
循环:
while ((match = regex.exec( text )) != null)
{
console.log(match);
}
要一次获得所有匹配项,请使用 text.match(regex)
,其中正则表达式指定了 g
(全局标志)。 g
标志将使 match
找到字符串中正则表达式的所有匹配项,并返回数组中的所有匹配项。
[编辑] 这就是为什么我的示例设置了 g 标志! [/eoe]
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
// Note the g flag
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gm;
var match = text.match( regex );
console.log(match);
简单测试:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
// Note the g flag
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gi;
var n = text.match( regex );
alert(n);
}
</script>
工作完美...
关于Javascript 正则表达式再次捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707360/