Javascript regex multiple captures again

后端 未结 2 1426
天涯浪人
天涯浪人 2020-12-20 17:07

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

Javascript Regex group multiple

with a full example. I have:

        var text         


        
相关标签:
2条回答
  • 2020-12-20 17:48

    This is what works:

               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)
    

    Notice the /g which seems to be neccessary

    0 讨论(0)
  • 2020-12-20 18:04

    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);
    }
    

    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.

    [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);
    

    SIMPLE TEST:

    <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>
    

    working perfectly...

    0 讨论(0)
提交回复
热议问题