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

Deadly 提交于 2021-02-16 08:59:34

问题


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?


回答1:


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|$)



回答2:


@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



来源:https://stackoverflow.com/questions/19587328/extracting-key-value-pairs-with-regex-dot-group-not-cooperating-wit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!