2

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?

Maschina
  • 755
  • 7
  • 30
Nikabalte
  • 33
  • 3

2 Answers2

4

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]}`);
}
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
1

Use String.prototype.matchAll and Array.prototype.reduce to reduce it to an Object of key:value pairs

const s = "TEST_firstname:john_lastname:doe_age:45";
const m = s.matchAll(/([^:_]+):([^_]+)/g);
const user = [...m].reduce((ob, [m,k,v]) => (ob[k] = v, ob), {});

console.log(user);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313