Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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
Python正则表达式匹配组的对象数超过预期_Python_Regex - Fatal编程技术网

Python正则表达式匹配组的对象数超过预期

Python正则表达式匹配组的对象数超过预期,python,regex,Python,Regex,我正在使用re.search解析一行3个独立的数据段。(日期温度和压力)管线看起来像这样 line= "2015-10-08-22-50 27.3 1015.03" 我想使用模式匹配,这样我就可以对格式错误的行非常健壮。因此,使用拆分失败 我建造了一座新大楼 m= re.search("^(2\d{3}-\d{2}-\d{2}-\d{2}-\d{2})\s+(\d+.\d+)\s+(\d+.\d+)$", line) 解析很好,但是匹配组让我惊讶 >>> m.gro

我正在使用re.search解析一行3个独立的数据段。(日期温度和压力)管线看起来像这样

line= "2015-10-08-22-50   27.3   1015.03"
我想使用模式匹配,这样我就可以对格式错误的行非常健壮。因此,使用拆分失败

我建造了一座新大楼

m= re.search("^(2\d{3}-\d{2}-\d{2}-\d{2}-\d{2})\s+(\d+.\d+)\s+(\d+.\d+)$", line)
解析很好,但是匹配组让我惊讶

>>> m.groups(1)
('2015-10-08-23-00', '27.3', '1014.99')
>>> m.groups(2)
('2015-10-08-23-00', '27.3', '1014.99')
>>> m.groups(3)
('2015-10-08-23-00', '27.3', '1014.99')
我(天真地)预料到了

>>> m.groups(1)
('2015-10-08-23-00')
>>> m.groups(2)
('27.3')
>>> m.groups(3)
('1014.99')
现在我通过使用索引来解决这个问题

dt= m.groups(1)[0]
t = m.groups(2)[1]
p = m.groups(3)[2]
我的结论是,我认为还可以的re一定有缺陷或者不尽可能干净

少了什么

谢谢,
Gert

m.groups()的参数不是要返回哪个捕获组。这是一个可选的默认值,可用于任何不匹配的捕获组。无论哪种方式,函数都会返回一个包含所有捕获组的列表,您必须对其进行索引才能获得特定的捕获组。

而不是:

m.groups(1)
我想你想要:

m.groups()[0]
groups()的参数是一个默认值,而不是它返回的元组中的位置。所以你不需要通过任何考试。您确实需要索引它返回的元组

help(m.groups)
Help on built-in function groups:

groups(...)
    groups([default=None]) -> tuple.

    Return a tuple containing all the subgroups of the match, from 1.
    The default argument is used for groups
    that did not participate in the match

你的模式没有问题

您可以使用命名组来澄清:

>>> pat=re.compile(r"""^(?P<date>2\d{3}-\d{2}-\d{2}-\d{2}-\d{2})\s+
...                     (?P<temp>\d+.\d+)\s+
...                     (?P<pres>\d+.\d+)$""", re.X)
>>> line= "2015-10-08-22-50   27.3   1015.03"
>>> m=pat.search(line)
但也可以像往常一样访问:

>>> m.group(1)
'2015-10-08-22-50'
>>> m.group(2)
'27.3'
或者为
groups()
返回的元组编制索引,但我认为这不是很清楚(正如您似乎已经发现的那样…)

如果你使用命名组,你会得到最好的世界

>>> m.groupdict()
{'date': '2015-10-08-22-50', 'temp': '27.3', 'pres': '1015.03'}
>>> m.group('date')
'2015-10-08-22-50'
>>> m.group('temp')
'27.3'
>>> m.group(1)
'2015-10-08-22-50'
>>> m.group(2)
'27.3'
>>> m.groups()[2]
'1015.03'