Javascript正则表达式多次捕获

时间:2013-02-05 12:17:01

标签: javascript regex

好的,我想我需要重新发布原来的问题:

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的输出为:

Output from console.log

问题是我只得到第一个结果...... 不是其他......我能做些什么来捕捉和遍历所有匹配的东西?

2 个答案:

答案 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 似乎是必要的