re.fullmatch() 可以消除正则表达式中对字符串锚点的需要吗

Chr*_*ris 1 python regex

考虑以下正则表达式,它检查密码强度。它具有开始和结束字符串锚点,以确保它匹配整个字符串。

pattern = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&.])[A-Za-z\d$@$!%*#?&.]{8,}$')
    while True:
        user_pass = input('Enter a secure password: ')
        if re.fullmatch(pattern, user_pass):
            print('Successfully changed password')
            break
        else:
            print('Not secure enough. Ensure pass is 8 characters long with at least one upper and lowercase letter, number,'
                  ' and special character.')
Run Code Online (Sandbox Code Playgroud)

我注意到 Python 3.5 有一个 re.fullmatch() 似乎做同样的事情,但没有字符串锚点:

pattern = re.compile(r'(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&.])[A-Za-z\d$@$!%*#?&.]{8,}')
while True:
    user_pass = input('Enter a secure password: ')
    if re.fullmatch(pattern, user_pass):
        print('Successfully changed password')
        break
    else:
        print('Not secure enough. Ensure pass is 8 characters long with at least one upper and lowercase letter, number,'
              ' and special character.')
Run Code Online (Sandbox Code Playgroud)

这是 fullmatch 的预期目的吗?是否有任何情况会导致意外问题?

Del*_*gan 5

fullmatch()函数和regex.fullmatch()方法在Python 3.4是新的

变更日志对此非常明确:

这提供了一种明确匹配目标的方法,从而避免了一类微妙的错误,即在代码更改或向现有正则表达式添加替代项期间 $ 字符丢失的情况。

因此,您使用它的方式确实是此功能的预期目的。它不能导致意想不到的问题,^$只是谨慎内部添加。

  • [Tim Peters 观察](https://bugs.python.org/issue16203) `re.match(r'a|ab$', 'ab').group()` 返回 `'a'`,而 `re .fullmatch(r'a|ab', 'ab').group()` 返回 `'ab'`。所以`re.fullmatch(...)` 不仅仅是`re.match('...$')` 的替代品。这很微妙。 (4认同)
  • 我认为这实际上是一个支持 fullmatch 的例子 - 原始的 re 可能应该写成 re.match(r'(a|ab)$', 'ab').group() 但缺少括号导致了结束 -锚定“$”仅与交替的“ab”分支相关联。 (2认同)