本文介绍了使用正则表达式提取 `<key>=<value>` 对,点组 (.+?) 不与可选空格 (\s) 合作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

metadata=1.2 name=stone:supershare UUID=eff4e7bc:47aea5cf:0f0560f0:2de38475

我希望从中提取键值对:=.

/(\w+)=(.+?)\s/g

正如预期的那样,由于后面没有空格,因此不会返回 UUID 对:

[元数据=1.2",名称=石头:超级共享"],["元数据",名称"],["1.2",石头:超级共享"]

现在,很明显,我们应该让 \s 查找成为可选的:

/(\w+)=(.+?)\s?/g

尽管如此,仅从 value 中提取第一个符号是完全疯狂的:

["元数据=1","姓名=s",UUID=e"],["元数据",名称",UUID"],["1","s",电子"]

我有点迷茫,我在这里做错了什么?

解决方案

由于 \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|$)

这篇关于使用正则表达式提取 `&lt;key&gt;=&lt;value&gt;` 对,点组 (.+?) 不与可选空格 (\s) 合作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:11