简体   繁体   English

检查输入python正则表达式的有效性

[英]check validity of an input python regex

I want to check input with format of username@websitename.extension with following properties:我想使用 username@websitename.extension 格式检查输入,并具有以下属性:

  • username should only contain digits, alphabet and -,_用户名只能包含数字、字母和 -,_
  • websitename should only contain digits and alphabet网站名称应仅包含数字和字母
  • the length of extension must be at most 3扩展的长度最多为 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.表达式\\.{3}匹配三个文字点。 Presumably you want \\.[az]{3}$大概你想要\\.[az]{3}$

For the hostname part, [az] obviously does not include digits;对于主机名部分, [az]显然不包含数字; try [a-z0-9] .试试[a-z0-9]

There's no particular benefit from doing compile on a regex you immediately throw away.在您立即丢弃的正则表达式上进行compile没有特别的好处。

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}$ .如果你想接受子域(你可能应该),你可以在@ ,在[az]{3}$之前添加一个重复,比如([a-z0-9]+\\.)+

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.无论如何,这会以不同的原因拒绝我的首选、我的备份和我的第三级电子邮件地址。

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

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