3

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?

4

2 回答 2

4

@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

于 2013-10-25T10:58:29.663 回答
2

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|$)
于 2013-10-25T10:37:09.483 回答