How to capture multiple repeated groups?

前端 未结 7 1526
傲寒
傲寒 2020-11-22 10:59

I need to capture multiple groups of the same pattern. Suppose, I have a following string:

HELLO,THERE,WORLD

And I\'ve written a following

7条回答
  •  不思量自难忘°
    2020-11-22 11:28

    You actually have one capture group that will match multiple times. Not multiple capture groups.

    javascript (js) solution:

    let string = "HI,THERE,TOM";
    let myRegexp = /([A-Z]+),?/g;       //modify as you like
    let match = myRegexp.exec(string);  //js function, output described below
    while(match!=null){                 //loops through matches
        console.log(match[1]);          //do whatever you want with each match
        match = myRegexp.exec(bob);     //find next match
    }
    

    Output:

    HI
    THERE
    TOM
    

    Syntax:

    // matched text: match[0]
    // match start: match.index
    // capturing group n: match[n]
    

    As you can see, this will work for any number of matches.

提交回复
热议问题