好的,我想我需要重新发布原来的问题:
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的输出为:
问题是我只得到第一个结果...... 不是其他......我能做些什么来捕捉和遍历所有匹配的东西?
答案 0 :(得分:14)
exec
一次只返回一个结果,并将指针设置为该匹配的结尾。因此,如果您想获得所有匹配,请使用while
循环:
while ((match = regex.exec( text )) != null)
{
console.log(match);
}
要一次性获取所有匹配项,请使用text.match(regex)
,其中正则表达式指定了g
(全局标记)。 g
标志将使match
找到字符串中正则表达式的所有匹配项,并返回数组中的所有匹配项。
[编辑] 这就是为什么我的例子设置了标志! [/ 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>
完美地工作......
答案 1 :(得分:2)
这是有效的:
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]*?)>/g;
var match = null;
while ( (match = regex.exec( text )) != null )
console.log(match)
注意 / g 似乎是必要的