Python 前瞻正则表达式中 .* 的用途是什么?

What is the purpose of .* in a Python lookahead regex?

我正在学习正则表达式,我发现了一个关于使用它们进行密码输入验证的有趣且有用的页面 here。我的问题是关于以下表达式中的 .*

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

我知道 .* 是一个代表任意数量文本(或无文本)的通配符,但我在这些前瞻表达式中无法理解它的用途。为什么需要这些才能使这些前瞻功能按需发挥作用?

前瞻意味着直接前瞻。所以如果你写:

(?=a)

表示第一个字符应该是a。有时,例如密码检查,您不希望这样。你想表达某处应该有一个 a。所以:

(?=.*a)

表示第一个字符可以是 b8@。但最终应该有一个 a 某处。

你的正则表达式意味着:

^               # start a match at the beginning of the string
(?=.*[a-z])     # should contain at least one a-z character
(?=.*[A-Z])     # should contain at least one A-Z character
(?=.*\d)        # should contain at least one digit
[a-zA-Z\d]{8,}  # consists out of 8 or more characters and only A-Za-z0-9
$               # end the match at the end of the string

如果没有 .*,就永远不会匹配 ,因为:

 "^(?=[a-z])(?=[A-Z])(?=\d)[a-zA-Z\d]{8,}$"

表示:

^               # start a match at the beginning of the string
(?=[a-z])       # first character should be an a-z character
(?=[A-Z])       # first character should be an A-Z character
(?=\d)          # first character should be a digit
[a-zA-Z\d]{8,}  # consists out of 8 or more characters and only A-Za-z0-9
$               # end the match at the end of the string

因为不存在既是A-Z字符又是数字的字符。这永远不会满足。

旁注:

  1. 我们在前瞻中捕获,所以贪婪并不重要;
  2. . 默认为 ;
  3. 即使它做了你有约束的事实^[A-Za-z0-9]{8,}$意味着你只会验证没有换行的输入。