How to capture multiple repeated groups?

前端 未结 7 1626
傲寒
傲寒 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:24

    Sorry, not Swift, just a proof of concept in the closest language at hand.

    // JavaScript POC. Output:
    // Matches:  ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]
    
    let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
    let matches = [];
    
    function recurse(str, matches) {
        let regex = /^((,?([A-Z]+))+)$/gm
        let m
        while ((m = regex.exec(str)) !== null) {
            matches.unshift(m[3])
            return str.replace(m[2], '')
        }
        return "bzzt!"
    }
    
    while ((str = recurse(str, matches)) != "bzzt!") ;
    console.log("Matches: ", JSON.stringify(matches))
    

    Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.

提交回复
热议问题