问题描述
我有这个字符串:
metadata=1.2 name=stone:supershare UUID=eff4e7bc:47aea5cf:0f0560f0:2de38475
我希望从中提取键值对:=
.
/(\w+)=(.+?)\s/g
正如预期的那样,由于后面没有空格,因此不会返回 UUID
对:
现在,很明显,我们应该让 \s
查找成为可选的:
/(\w+)=(.+?)\s?/g
尽管如此,仅从 value
中提取第一个符号是完全疯狂的:
我有点迷茫,我在这里做错了什么?
由于 \s
不是必需的,所以前面的 (.+?)
部分是免费的只匹配一个字符,这是由于 ?
它将尝试执行的操作.您可以:
- 将
(.+?)
更改为(.+)
但如果您的值可以包含空格或 ,则可能会导致其他问题 - 将
\s?
改为(?:\s|$)
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?
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|$)
这篇关于使用正则表达式提取 `<key>=<value>` 对,点组 (.+?) 不与可选空格 (\s) 合作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!