Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 用python提取正则表达式字段_Regex - Fatal编程技术网

Regex 用python提取正则表达式字段

Regex 用python提取正则表达式字段,regex,Regex,我有这样一个字符串: 字段1:value1字段2:value2 字段可以有空格,例如字段名:但值字段永远不会有空格 使用正则表达式将字段值对提取为数字组而不事先知道字段名的简单方法是什么 我正在使用pythonb 谢谢 这是使用使用以下正则表达式填充的词典理解: ([^:]+) # one or more characters except : (--> group(1)) : # a literal : (\S+) # one or more non-whitespac

我有这样一个字符串:

字段1:value1字段2:value2

字段可以有空格,例如字段名:但值字段永远不会有空格

使用正则表达式将字段值对提取为数字组而不事先知道字段名的简单方法是什么

我正在使用pythonb

谢谢

这是使用使用以下正则表达式填充的词典理解:

([^:]+) # one or more characters except :  (--> group(1))
:       # a literal :
(\S+)   # one or more non-whitespace characters (--> group(2))
\s*     # optional trailing whitespace (before the next match)
这是使用使用以下正则表达式填充的词典理解:

([^:]+) # one or more characters except :  (--> group(1))
:       # a literal :
(\S+)   # one or more non-whitespace characters (--> group(2))
\s*     # optional trailing whitespace (before the next match)

也许是这样的

([^:]+:[^ ]*)*

也许是这样的

([^:]+:[^ ]*)*
您可以使用re.findall执行您想要的操作:

>>> data = "field1:value1 field2:value2 field with space:something"
>>> re.findall(r'\s*([^:]+):(\S+)', data)
[('field1', 'value1'), ('field2', 'value2'), ('field with space', 'something')]
您可以使用re.findall执行您想要的操作:

>>> data = "field1:value1 field2:value2 field with space:something"
>>> re.findall(r'\s*([^:]+):(\S+)', data)
[('field1', 'value1'), ('field2', 'value2'), ('field with space', 'something')]