匹配特定长度的字母数字字符串

3 投票
1 回答
3277 浏览
提问于 2025-04-16 23:55

我有一个练习题,但不知道怎么解决:

我只能接受一个字符串,这个字符串必须由数字和字母组成,至少要包含其中一个;而且它的长度要在6到8个字符之间。这个字符串只能是一个单词。

前面的部分我做得还不错,不过我不太确定用match这个方法是否合适:

re.match('([a-zA-Z]+[0-9]+)', string)

但是我不知道怎么指定这个字符串的长度,应该是数字和字母加起来的总长度。这样做是行不通的,我想这样也不应该:

re.match('([a-zA-Z]+[0-9]+){6,8}', string)

谢谢你的帮助。

1 个回答

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.

撰写回答