【问题标题】:Can't form a Regexp with a Multiline in Python [duplicate]无法在 Python 中使用多行形成正则表达式 [重复]
【发布时间】:2018-12-14 22:37:01
【问题描述】:

我正在尝试运行以下正则表达式:

password_regexp = re.compile(r'''^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+.{6,}$''')

它按预期工作。为了可读性,我决定把它隔开,因为它是多行的:

password_regexp = re.compile(r'''(
    ^(?=.*[a-z])
    (?=.*[A-Z])
    (?=.*\d)
    .+.{6,}$
    )''')

当我运行以下代码(适用于单行版本)时:

why = password_regexp.search(password)
why.group()

我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

为什么?单行版本可以,为什么放在多行加上'''会毁了它?

【问题讨论】:

    标签: python regex multiline


    【解决方案1】:

    您需要使用re.VERBOSE 标志并删除多余的括号。

    password_regexp = re.compile(r'''
        ^(?=.*[a-z])
        (?=.*[A-Z])
        (?=.*\d)
        .+.{6,}$
    ''', re.VERBOSE)
    

    【讨论】:

    • 字面是要删了,谢谢帮忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2022-11-15
    • 2013-04-15
    • 1970-01-01
    • 2015-10-01
    • 2021-05-08
    相关资源
    最近更新 更多