Search code examples
javascriptregexregex-group

How to use regex groups to split key & values


I have some data I would like to extract to build an object in JS but I can't find how to do with regex.

On regex101 the regex below seems to fit but it doesn't in my code...

Here is the type of data:

"TEST_firstname:john_lastname:doe_age:45"

And I would want to extract key and values (key is between "_" and ":", value is between ":" and "_"

I tried with this : (?<key>(?<=\_)(.*?)(?=\:))|(?<value>(?<=\:)(.*?)((?=\_)|$))

Could someone help me to find the good regex?


Solution

  • Use

    /([^_:]+):([^_]+)/g
    

    See regex proof.

    EXPLANATION

    --------------------------------------------------------------------------------
      (                        group and capture to \1:
    --------------------------------------------------------------------------------
        [^_:]+                   any character except: '_', ':' (1 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
      )                        end of \1
    --------------------------------------------------------------------------------
      :                        ':'
    --------------------------------------------------------------------------------
      (                        group and capture to \2:
    --------------------------------------------------------------------------------
        [^_]+                    any character except: '_' (1 or more
                                 times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
      )                        end of \2
    

    JavaScript code:

    const regex = /([^_:]+):([^_]+)/g;
    const str = `TEST_firstname:john_lastname:doe_age:45`;
    while ((m = regex.exec(str)) !== null) {
        console.log(`${m[1]} >>> ${m[2]}`);
    }