Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting `<key>=<value>` pairs with regex, dot group (.+?) not cooperating with optional space (\s)

Tags:

regex

pcre

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?

like image 259
tomsseisums Avatar asked Dec 03 '25 14:12

tomsseisums


2 Answers

@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

like image 193
Ibrahim Najjar Avatar answered Dec 06 '25 07:12

Ibrahim Najjar


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:

  • change (.+?) to (.+) but that might cause other issues if your values can include spaces or
  • change \s? to (?:\s|$)
like image 43
acfrancis Avatar answered Dec 06 '25 06:12

acfrancis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!