在Python lookahead正则表达式中。*的用途是什么?

问题描述:

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

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

我明白.*是表示文本(或无文本)的任何量通配符,但我有麻烦缠绕我的头周围它在这些先行表达式中的用途。为了使这些预见功能符合需要,为什么需要这些功能?

+0

*最终*你会找到一个'[a-z]'等等 –

+0

@WillemVanOnsem yea但是。*是贪婪的。点doens't线断裂。所以这可能是他们正在寻找一个换行符,然后是任何字母字符? – Jerinaw

+1

@Jerinaw:对于lookahead等,没有贪婪因素,因为它不捕获*。通常换行符*不包含在点“。”中。 –

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

(?=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 

既然有没有既是一个AZ特征的字符ter和一个数字。这永远不会得到满足。

旁注:

  1. 我们在先行拍摄图像,以便greedyness不要紧;
  2. .默认为not match the new line character;
  3. 即使它确实有约束^[A-Za-z0-9]{8,}$这一事实意味着您只会验证没有换行的输入。