Home > Mobile >  Python regex to match a pattern that starts with word, end with 4 digits, contain no special charact
Python regex to match a pattern that starts with word, end with 4 digits, contain no special charact

Time:11-17

I am new to regex and is looking for a regex pattern to check if the matched string fulfills the below 4 criteria:

  1. Starts with word "user"
  2. Ends with set of 4 digit random number.
  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.

Example of matched pattern:

userjoe@manhattan34 user%ryan%@nashville3354

I tried using below code but it does not work:

inputstr = "userjoe@manhattan34"
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. Also string length check validation is missing in the above code

CodePudding user response:

I would use the following regex pattern:

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

Python script, using re.search:

inputstr = 'userjoe@manhattan34'
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
$
  • Related