我有以下代码注释: Line变量来自我正在读取的文本文件中的一行,pattern变量保存在配置文件中,我选择该文件并将其应用于代码中
line ="[u'INVOICE# SMR/0038 f"', u'', u'', u'']"
pattern ='(?<=(invoice#)\s)[A-z]{3}/\d{1,5}'
regex = re.compile(r'' + pattern),re.IGNORECASE)
invNum= re.findall(pattern, str(line),re.IGNORECASE)[0]
........我期望得到invNum = SMR/0038,但我得到的却是invoice#。问题出在哪里?如果在https://regexr.com/上尝试此模式,我看到后视功能正在工作。但是把它转换成Python代码是行不通的。请参阅来自https://regexr.com/的下图
发布于 2019-09-16 17:46:28
由于模式中的re.findall returns the captured substring only if there is a capturing group,所以在使用捕获组包装invoice#子字符串时,您将获得它。
另外,请注意[A-z] matches more than just ASCII letters,它是正则表达式世界中最令人困惑的模式之一。使用[A-Za-z]。
你需要捕获你想要提取的部分,你甚至不需要后视:
import re
line ="[u'INVOICE# SMR/0038 f\"', u'', u'', u'']"
pattern = re.compile('invoice#\s+([A-Za-z]{3}/\d{1,5})', re.I)
print( re.findall(pattern, line) ) # => ['SMR/0038']请参阅online demo
实际上,因为您需要to get the first match only, use re.search (re.findall返回所有匹配项):
m = pattern.search(line)
if m:
print(m.group(1)) # => SMR/0038https://stackoverflow.com/questions/57954142
复制相似问题