【发布时间】:2020-04-11 22:40:46
【问题描述】:
我有一个带有一些文本的 .txt 文件(从 edifact 文件复制),我想匹配某些字段,我基本上只想要日期(匹配 1,组 0)
这是我拥有的正则表达式 https://regex101.com/r/oSVlS8/6
但我无法在我的代码中实现它,我只想要匹配的第 0 组。
这是我的代码:
regex = r"^((?:INV)\+(?:[^+\n]*\+){4})\d{8}"
with open ("test edifakt 1 bk v1.txt", "r") as f:
result = re.findall(regex,f.read(),re.MULTILINE)
print(result)
这就是我得到的结果:
['INV+ED Format 1+Brustkrebs+19880117+E000000001+']
我实际上想要“20080702”
我尝试了print(result.group(0)) 之类的方法,但没有奏效。我得到了:AttributeError: 'list' object has no attribute 'group'
我也尝试将它作为这样的论点 result = re.findall(regex,f.read(),group(0),re.MULTILINE) 但我得到get NameError: name 'group' is not defined
如果我使用re.search 及其字符串,我真的只能匹配某个组吗?
【问题讨论】:
-
尝试切换组
\bINV\+(?:[^+\n]*\+){4}(\d{8})regex101.com/r/i5MedI/1,值将在组1中 -
re.findall() returns a list,所以,如果您想要第一场小组赛,请使用re.findall()[0]。