正则表达式提取由空格分隔的键值对,其值为空格 [英] Regex to extract key-value pairs separated by space, with space in values
问题描述
假设一个单行字符串,其中包含多个连续的键值对,用空格分隔,但允许的值也在值内(不在键中),例如
Assume a one-line string with multiple consecutive key-value pairs, separated by a space, but with space allowed also within values (not in keys), e.g.
key1=one two three key2=four key3=five six key4=seven eight nine ten
从上面正确提取键值对会产生以下映射:
Correctly extracting the key-value pairs from above would produce the following mappings:
"key1", "one two"
"key2", "four"
"key3", "five six"
"key4", "seven eight nine ten"
其中keyX可以是任何字符序列,不包括空格。
where "keyX" can be any sequence of characters, excluding space.
尝试简单的事情,比如
([^=]+=[^=]+)+
或类似的变化是不够的。
or similar variations is not adequate.
是否有正则表达式可以完全处理这样的提取,没有任何进一步的字符串处理?
Is there a regex to fully handle such extraction, without any further string processing?
推荐答案
尝试lookah ead :
(\b\w+)=(.*?(?=\s\w+=|$))
作为Java字符串:
"(\\b\\w+)=(.*?(?=\\s\\w+=|$))"
在regex101.com进行测试; 在regexplanet上测试(点击Java)
Test at regex101.com; Test at regexplanet (click on "Java")
这篇关于正则表达式提取由空格分隔的键值对,其值为空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!