【问题标题】:Python regex compile (with re.VERBOSE) not workingPython 正则表达式编译(使用 re.VERBOSE)不起作用
【发布时间】:2012-12-07 10:58:41
【问题描述】:

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

(使用 Python 3.3.0)

之前:

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

输出:杜克·万恩

之后:

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”对象没有属性“组”

【问题讨论】:

标签: python regex


【解决方案1】:

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

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

【讨论】:

  • 这是否需要在正则表达式中将所有文字空格替换为[ ]?据我所知,情况似乎如此。
  • @Brad 是的。它们需要按照文档提到的一种方式明确说明
  • 实际上这是原始多行字符串的错误语法:r'''this is wrong'''。正确的语法必须使用带双引号的 r:r"""this is right"""。见How to correctly write a raw multiline string in Python?
  • @smci 就语法而言,它们是一回事,所以虽然有人可能认为使用引号更像 PEP8,但我不确定你为什么断言一个是正确的并且其他不是……?
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多