所以我有这个练习,无法解决它:
我只能接受一个字符串,如果它由数字和字母构成,则必须包含至少两个字符串;它必须是6-8个字符长。字符串只有一个字。
第一部分很好,但我不确定使用匹配:
re.match('([a-zA-Z]+[0-9]+)', string)
但我不知道如何指定长度应该是加起来的数字和字母的长度。这不起作用,我想不管怎么说:
re.match('([a-zA-Z]+[0-9]+){6,8}', string)
感谢您的帮助。
答案 0 :(得分:7)
试试这个:
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z\d]{6,8}$
说明:
^ //The Start of the string
(?=.*\d) //(?= ) is a look around. Meaning it
//checks that the case is matched, but
//doesn't capture anything
//In this case, it's looking for any
//chars followed by a digit.
(?=.*[a-zA-Z]) //any chars followed by a char.
[a-zA-Z\d]{6,8}//6-8 digits or chars.
$ //The end of the string.