我试图在用户输入的字符串中找到重复超过 2 次的字符。我有这个,但它没有进入 if 语句。
password = asDFwe23df333
s = re.compile('((\w)\2{2,})')
m = s.search(password)
if m:
print ("Password cannot contain 3 or more of the same characters in a row\n")
sys.exit(0)
我试图在用户输入的字符串中找到重复超过 2 次的字符。我有这个,但它没有进入 if 语句。
password = asDFwe23df333
s = re.compile('((\w)\2{2,})')
m = s.search(password)
if m:
print ("Password cannot contain 3 or more of the same characters in a row\n")
sys.exit(0)
您需要在您的正则表达式前加上字母“r”,如下所示:
s = re.compile(r'((\w)\2{2,})')
如果您不这样做,那么您将不得不加倍所有反斜杠,因为 Python 通常将反斜杠视为其正常字符串中的转义字符。由于这使得正则表达式比通常更难阅读,因此 Python 中的大多数正则表达式都包含该前缀。
此外,在您包含的代码中,您的密码不在引号中,但我假设它在您的代码中包含引号。
难道你不能简单地遍历整个字符串,每次你找到一个等于前一个字符的时候,你就增加一个计数器,直到它达到 3 的值?如果字符与以前不同,只需将计数器设置回 0 即可。
编辑:或者,您可以使用:
s = 'aaabbb' re.findall(r'((\w)\2{2,})', s)
并检查第二行返回的列表是否有任何元素。