RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1602
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  面向向阳花
    2020-11-22 03:08

    My guess is that if there would be edge cases such as extra or missing spaces, this expression with less boundaries might also be an option:

    ^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$
    

    If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    Test

    const regex = /^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$/gm;
    const str = `[description:"aoeu" uuid:"123sth"]
    [description : "aoeu" uuid: "123sth"]
    [ description : "aoeu" uuid: "123sth" ]
     [ description : "aoeu"   uuid : "123sth" ]
     [ description : "aoeu"uuid  : "123sth" ] `;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    RegEx Circuit

    jex.im visualizes regular expressions:

提交回复
热议问题