Python Django模型中域名的正则表达式匹配
我有一张桌子,看起来像:Python Django模型中域名的正则表达式匹配,python,regex,django,model,Python,Regex,Django,Model,我有一张桌子,看起来像: class Tld(models.Model): domainNm = models.CharField(validators=[ RegexValidator('^[0-9]^[a-z]','yourdomain.com only','Invalid Entry')], max_length=40) dtCreated = models.DateField() 对于domainNm-我想验证以下任何条目: class Tld(models.Model
class Tld(models.Model):
domainNm = models.CharField(validators=[ RegexValidator('^[0-9]^[a-z]','yourdomain.com only','Invalid Entry')], max_length=40)
dtCreated = models.DateField()
对于domainNm-我想验证以下任何条目:
class Tld(models.Model):
domainNm = models.CharField(validators=[ RegexValidator('^[0-9]^[a-z]','yourdomain.com only','Invalid Entry')], max_length=40)
dtCreated = models.DateField()
- domain.com
- 1domain.com
- 域名1.com
[com | biz | net]
等,并且是字母数字
如何在django模型的模型级别上执行此操作
谢谢如果要验证HTTP URL,请忘记正则表达式并使用 如果您只想要没有任何协议的域,请尝试:
def full_domain_validator(hostname):
"""
Fully validates a domain name as compilant with the standard rules:
- Composed of series of labels concatenated with dots, as are all domain names.
- Each label must be between 1 and 63 characters long.
- The entire hostname (including the delimiting dots) has a maximum of 255 characters.
- Only characters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9'.
- Labels can't start or end with a hyphen.
"""
HOSTNAME_LABEL_PATTERN = re.compile("(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
if not hostname:
return
if len(hostname) > 255:
raise ValidationError(_("The domain name cannot be composed of more than 255 characters."))
if hostname[-1:] == ".":
hostname = hostname[:-1] # strip exactly one dot from the right, if present
for label in hostname.split("."):
if len(label) > 63:
raise ValidationError(
_("The label '%(label)s' is too long (maximum is 63 characters).") % {'label': label})
if not HOSTNAME_LABEL_PATTERN.match(label):
raise ValidationError(_("Unallowed characters in label '%(label)s'.") % {'label': label})
或
为了重述上述澄清:您只想匹配具有单个字母数字标签和最多4个字符的TLD的域,例如“domain.com”或“someotherdomain.info”或“345xyz.pdq1”,但不匹配“subdomain.domain.com”、“www.domain.com”或“345xyz.abcde”。此正则表达式将执行以下操作:
^[a-z0-9]+\.[a-z0-9]{1,4}$
这是一个无效的正则表达式。^匹配字符串的开头。除非用|隔开,否则在那里放两次是没有意义的。不管怎样,不清楚你想要匹配什么。您是在尝试确保字符串以字母数字字符开头,还是整个字符串都是字母数字加点,并且可能是以“http://”开头,或者什么?请尽量具体,并举例说明您希望正则表达式匹配的内容以及您希望它拒绝的内容。请参阅更新的问题。很抱歉弄错了,那么您现在是说如果它以“www”或“http://”开头,您不希望匹配,如果其中任何一个在域之前,您仍然希望匹配吗?另外,是否要将其限制为单个点,或者如果存在子域,是否也要进行匹配?regex
^[a-z0-9]+\(com | biz | net)$
将验证字符串是否符合您在修订的问题中描述的格式,但我不确定这是否是您真正想要的。应该http://domain.com
和/或subdomain.domain.com
匹配或失败?您声明的正则表达式是正确的,但如何使域扩展(例如com、biz、net)更具动态性,即只允许字母字符,最多只允许4个字母字符?e、 g.com、biz、net都可以,但是允许类似信息的东西,而不需要正则表达式说明域扩展?另外,请在问题中陈述您的意见。我认为这应该是公认的答案,因为它指出了验证程序的存在-OP要求顶级域(不是完整域)这个验证器将允许一个主机名,比如:domain(没有tld),这是非常有限的。ie:express.co.uk会破坏www.*域(即使你提到了,我还是坚持)。
^[a-z0-9]+\.[a-z0-9]{1,4}$