How would you validate a string to check if it follows this format?

Viewed 88

I would like to check if the string stored in the variable, Username is stored in the following format:

"a.bcde" or "12a.bcde"

Before the full stop, there can be a single letter or two numbers and a letter.

After the full stop, there can only be letters.

Valid Strings: "a.bcdefghi","45z.yxwu"

Invalid Strings: "1a.bcdef","12a.bcde@"

I had written the following code

if bool(re.match("..[a-z][.][a-z]+", Username))==True:
      return True
else:
      return False

However, it returns False for "a.bcde" and True for "12a.bcde@fgh.com"

1 Answers

You can use

^(?:\d{2})?[a-z][.][a-z]+$
  • ^ Start of string
  • (?:\d{2})? Optionally match 2 digits
  • [a-z][.] Match a single char a-z and .
  • [a-z]+ Match 1+ chars a-z
  • $ End of string

Regex demo | [Python demo(https://ideone.com/k2Hk81)]

For example

import re

pattern = r"(?:\d{2})?[a-z][.][a-z]+$"
strings = [
    "a.bcde",
    "12a.bcde",
    "a.bcdefghi",
    "45z.yxwu",
    "1a.bcdef",
    "12a.bcde@"
]

for s in strings:
    m = re.match(pattern, s)
    if m:
        print("Match for {0}".format(m.group()))

Output

Match for a.bcde
Match for 12a.bcde
Match for a.bcdefghi
Match for 45z.yxwu
Related