开发者

Matching string of numbers and letters and of a specific length

So I have this exercise and can't solve it:

I can only accept a string, if it's constructed of numbers AND letters, has to contain at least one of both; and it has to be 6-8 characters long. The string is only one word.

The first part is fine, though I'm not sure about using match:

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

but I don't know how to specify the length that it should be the length of both numbers and letters added up. This won't work and I guess it shouldn't anyway:

re.match('([开发者_Python百科a-zA-Z]+[0-9]+){6,8}', string)

Thanks for your help.


Try this one:

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

Explanation:

^              //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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜