繁体   English   中英

Python正则表达式匹配以单词开头,以4位数字结尾,不包含除@和%之外的特殊字符并且至少有10个字符的模式

[英]Python regex to match a pattern that starts with word, end with 4 digits, contain no special characters except @ and % and have atleast 10 characters

我是 regex 的新手,正在寻找一个 regex 模式来检查匹配的字符串是否满足以下 4 个条件:

  1. 以单词“user”开头
  2. 以一组 4 位随机数结尾。
  3. 除了@ 和 % 之外,字符串应该没有特殊字符
  4. 它应该在匹配的字符串中至少有一个@ 符号和一个 % 符号。
  5. 总字符串长度应至少为 20 个字符。

匹配模式示例:

userjoe@manhattan%1234 user%ryan%@nashville3354

我尝试使用下面的代码,但它不起作用:

inputstr = "userjoe@manhattan%1234"
if re.match(r'^user.*%+.*@+.*\d{4}$',inputstr):
    print("True")
else:
    print("False")

当特殊符号改变字符串中的位置时(即 @ 先出现,然后是 %),输出为 false 而不是预期的 True 输出。 上面的代码中也缺少字符串长度检查验证

我将使用以下正则表达式模式:

^user(?=.*@)(?=.*%)[A-Za-z0-9@%]{12,}[0-9]{4}$

Python 脚本,使用re.search

inputstr = 'userjoe@manhattan%1234'
regex = r'^user(?=.*@)(?=.*%)[A-Za-z0-9@%]{12,}[0-9]{4}$'
if re.match(regex, inputstr):
    print("True")
else:
    print("False")

上面的正则表达式模式说要匹配:

^
user                starts with 'user'
(?=.*@)             assert that at least one @ appears
(?=.*%)             assert that at least one % appears
[A-Za-z0-9@%]{12,}  12 or more alphanumeric, @, %, characters
[0-9]{4}            ending in any 4 numbers
$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM