简体   繁体   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

I am new to regex and is looking for a regex pattern to check if the matched string fulfills the below 4 criteria:我是 regex 的新手,正在寻找一个 regex 模式来检查匹配的字符串是否满足以下 4 个条件:

  1. Starts with word "user"以单词“user”开头
  2. Ends with set of 4 digit random number.以一组 4 位随机数结尾。
  3. The string should have no special characters except @ and %除了@ 和 % 之外,字符串应该没有特殊字符
  4. It should at least have one @ symbol and one % symbol in the matched string.它应该在匹配的字符串中至少有一个@ 符号和一个 % 符号。
  5. The total string length should be at least 20 characters.总字符串长度应至少为 20 个字符。

Example of matched pattern:匹配模式示例:

userjoe@manhattan%1234 user%ryan%@nashville3354 userjoe@manhattan%1234 user%ryan%@nashville3354

I tried using below code but it does not work:我尝试使用下面的代码,但它不起作用:

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

When the special symbols change position in the string (ie @ comes first followed by %) output is false instead of expected output of True.当特殊符号改变字符串中的位置时(即 @ 先出现,然后是 %),输出为 false 而不是预期的 True 输出。 Also string length check validation is missing in the above code上面的代码中也缺少字符串长度检查验证

I would use the following regex pattern:我将使用以下正则表达式模式:

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

Python script, using re.search : 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")

The regex pattern above says to match:上面的正则表达式模式说要匹配:

^
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