好的,我想我需要重新发布原来的问题:
有一个完整的例子.我有:
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)
Run Code Online (Sandbox Code Playgroud)
console.log的输出是:

问题是我只得到了第一个...而不是其他的结果......我能做些什么来捕捉和遍历匹配的所有东西?
its*_*sid 15
exec一次只返回一个结果,并将指针设置为该匹配的结尾.因此,如果您想获得所有匹配,请使用while循环:
while ((match = regex.exec( text )) != null)
{
console.log(match);
}
Run Code Online (Sandbox Code Playgroud)
要一次性获取所有匹配项,请使用指定text.match(regex)正则表达式g(全局标志)的项目.该g标志将match查找字符串中正则表达式的所有匹配项并返回数组中的所有匹配项.
[编辑]这就是为什么我的例子HAD ag标志设置![/ 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);
Run Code Online (Sandbox Code Playgroud)
简单测试:
<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>
Run Code Online (Sandbox Code Playgroud)
完美地工作......