Python正则表达式编译(使用re.VERBOSE)不起作用

bfl*_*ang 9 python regex

我正在尝试在编译正则表达式时添加注释,但是当使用re.VERBOSE标志时,我再也没有得到任何匹配结果.

(使用Python 3.3.0)

之前:

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

输出: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())`
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*nts 10

空格被忽略(即,你的表达是有效的DukeWann),所以你需要确保那里有空格:

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

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

  • @smci 就语法而言,它们是相同的,所以虽然人们可能会争论使用引号更像是 PEP8,就像我不确定为什么你断言一个是正确的而另一个不是......? (2认同)