Javascript正则表达式再次捕获 [英] Javascript regex multiple captures again

查看:53
本文介绍了Javascript正则表达式再次捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我想我需要重新发布最初是我的问题:

Ok, I think I need to repost my question that was originally:

JavaScript正则表达式多组

带有完整的示例.我有:

with a full example. I have:

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

问题是我只得到第一个结果...别的……我该怎么做才能捕获并遍历所有匹配的东西?

The problem is that I am only getting the result for the first ... not the other... what can I do to be able to capture and walk over all stuff that matched?

推荐答案

exec 一次仅返回一个结果,并将指针设置为该匹配的结尾.因此,如果要获得所有匹配项,请使用 while 循环:

exec returns only ONE result at a time and sets the pointer to the end of that match. Therefore, if you want to get ALL matches use a while loop:

while ((match = regex.exec( text )) != null)
{
    console.log(match);
}

要一次获得所有匹配,请使用 text.match(regex),其中正则表达式指定了 g (全局标志). g 标志将使 match 查找字符串中与正则表达式的所有匹配项,并在数组中返回所有匹配项.

To get all matches at one shot, use text.match(regex), in which the regex has g (global flag) specified. The g flag will make match find all matches to the regex in the string and return all the matches in an array.

这就是为什么我的示例设置了g标志![/eoe]

[edit] and that's why my example HAD a g flag set! [/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正则表达式再次捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆