Javascript regex multiple captures again

后端 未结 2 1533
天涯浪人
天涯浪人 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条回答
  •  Happy的楠姐
    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 = ""+ 
               "                           " +
               "                           " +
               "                          " +
               "                           " +
               "       " +
               "        " +
               "                          " +
               "";
    
    // 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:

    
    
    
    

    working perfectly...

提交回复
热议问题