首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 2.7.16 - regex lookbehind不支持Findall

Python 2.7.16 - regex lookbehind不支持Findall
EN

Stack Overflow用户
提问于 2019-09-16 17:41:35
回答 1查看 200关注 0票数 1

我有以下代码注释: Line变量来自我正在读取的文本文件中的一行,pattern变量保存在配置文件中,我选择该文件并将其应用于代码中

代码语言:javascript
复制
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/的下图

sample from regexr

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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]

你需要捕获你想要提取的部分,你甚至不需要后视:

代码语言:javascript
复制
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返回所有匹配项):

代码语言:javascript
复制
m = pattern.search(line)
if m:
    print(m.group(1)) # => SMR/0038
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57954142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档