I have this string:
metadata=1.2 name=stone:supershare UUID=eff4e7bc:47aea5cf:0f0560f0:2de38475
I wish to extract from it the key and value pairs: <key>=<value>.
/(\w+)=(.+?)\s/g
This, as expected, doesn't return the UUID pair, due to not being followed by space:
[
"metadata=1.2 ",
"name=stone:supershare "
],
[
"metadata",
"name"
],
[
"1.2",
"stone:supershare"
]
Now, obviously, we should make the \s lookup optional:
/(\w+)=(.+?)\s?/g
Though, this goes utterly nuts extracting only the first symbol from value:
[
"metadata=1",
"name=s",
"UUID=e"
],
[
"metadata",
"name",
"UUID"
],
[
"1",
"s",
"e"
]
I am kind of lost, what am I doing wrong here?
@acfrancis explanation is correct, on the other hand you can try the following:
/(\w+)=([^\s]+)/g
This matches the <key> using (\w+) as in you original expression, but then it matches the value using ([^\s]+) which consumes one or more characters that are not white spaces.
Regex101 Demo
Since the \s isn't required, the previous part (.+?) is free to match just one character which is what it will try to do because of the ?. You can either:
(.+?) to (.+) but that might cause other issues if your values can include spaces or\s? to (?:\s|$)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With