Python 正则表达式编译(使用 re.VERBOSE)不起作用 [英] Python regex compile (with re.VERBOSE) not working

查看:60
本文介绍了Python 正则表达式编译(使用 re.VERBOSE)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在编译正则表达式时添加注释,但在使用 re.VERBOSE 标志时,我不再得到匹配结果.

I'm trying to put comments in when compiling a regex but when using the re.VERBOSE flag I get no matchresult anymore.

(使用 Python 3.3.0)

(using Python 3.3.0)

之前:

regex = re.compile(r"Duke wann", re.IGNORECASE)
print(regex.search("He is called: Duke WAnn.").group())

输出:Duke WAnn

Output: Duke WAnn

之后:

regex = re.compile(r'''
Duke # First name 
Wann #Last Name
''', re.VERBOSE | re.IGNORECASE)

print(regex.search("He is called: Duke WAnn.").group())`

输出:AttributeError: 'NoneType' 对象没有属性 'group'

Output: AttributeError: 'NoneType' object has no attribute 'group'

推荐答案

空格被忽略(即,您的表达式实际上是 DukeWann),因此您需要确保那里有一个空格:

Whitespaces are ignored (ie, your expression is effectively DukeWann), so you need to make sure there's a space there:

regex = re.compile(r'''
Duke[ ] # First name followed by a space
Wann #Last Name
''', re.VERBOSE | re.IGNORECASE)

http://docs.python.org/2/library/re.html#re.VERBOSE

这篇关于Python 正则表达式编译(使用 re.VERBOSE)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆