加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 匹配数字和字母以及特定长度的字符串

发布时间:2020-12-20 11:20:12 所属栏目:Python 来源:网络整理
导读:所以我有这个练习,无法解决它: 我只能接受一个字符串,如果它由数字和字母构成,则必须至少包含其中一个字符串;它必须是6-8个字符长.字符串只有一个字. 第一部分很好,虽然我不确定使用匹配: re.match('([a-zA-Z]+[0-9]+)',string) 但我不知道如何指定长度应
所以我有这个练习,无法解决它:

我只能接受一个字符串,如果它由数字和字母构成,则必须至少包含其中一个字符串;它必须是6-8个字符长.字符串只有一个字.

第一部分很好,虽然我不确定使用匹配:

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

但我不知道如何指定长度应该是加起来的数字和字母的长度.这不起作用,我想不管怎么说:

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

谢谢你的帮助.

解决方法

试试这个:

^(?=.*d)(?=.*[a-zA-Z])[a-zA-Zd]{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-Zd]{6,8}//6-8 digits or chars.
$             //The end of the string.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读