简体   繁体   中英

check validity of an input python regex

I want to check input with format of username@websitename.extension with following properties:

  • username should only contain digits, alphabet and -,_
  • websitename should only contain digits and alphabet
  • the length of extension must be at most 3

My following code does not work correctly. Can you help me with this?

def is_email_valid(email):
  rex = re.compile("[a-zA-Z0-9_-]+@[a-z]+\\.{3}")
  return rex.match(email)

The expression \\.{3} matches three literal dots. Presumably you want \\.[az]{3}$

For the hostname part, [az] obviously does not include digits; try [a-z0-9] .

There's no particular benefit from doing compile on a regex you immediately throw away.

def is_email_valid(email):
  return re.match(r"[a-zA-Z0-9_-]+@[a-z0-9]+\.[a-z]{3}$", email)

If you want to accept subdomains (and you probably should) you can add a repeat, like ([a-z0-9]+\\.)+ after the @ , before the [az]{3}$ .

Your criteria are much too strict for many valid email addresses, and will accept many invalid ones. Generally speaking, using regex to validate email addresses is a flawed idea, especially if your criteria for validity are completely ad hoc.

For what it's worth, this would reject my preferred, my backup, and my tertiary email addresses for different reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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