简单的域名正则表达式 [英] Simple regex for domain names

查看:212
本文介绍了简单的域名正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保域名与这3个简单的标准相符:




  • 以.com / .net结尾



不得以开头




  • http://或https://

  • http:// www。或https:// www。



我已经设法理解正确的这部分符合第一个标准的部分: p>

  /.*(\.com | \.net)$ / 
/ pre>

但是我不知道如何实现其他两个条件来制作一个独特的正则表达式。



感谢您的帮助。

解决方案

正则表达式解决方案很简单。简单地在字符串的开头显示一个负面的前瞻,如下所示:(with comments ...)

  if(preg_match('%
#匹配非http,com或.net域
^#开始字符串的锚点
(?!#断言这个URL不是...
https?://#HTTP或HTTPS方案与
(?:www \。)?#可选www。subdomain
)#结束负面前瞻
。*#匹配TLD
\##TLD前的最后一个字面值
(?:#组TLD替代品
net#Either .net
| com#或.com。
)#结束组TLD alts
$#锚点到字符串结束
%xi',$ text)){
// It火柴。
} else {
//它不匹配。
}

请注意,因为: http:// www。 是以下子集: http:// ,可选的 www。没有必要。这是一个较短的版本:

  if(preg_match('%^ //).*\.(?:net|com)$%i',$ text)){
//它匹配。
} else {
//它不匹配。
}

简单的正则表达式救援!


How to make sure that the domain name match those 3 simple criterias :

  • Ends with .com / .net

Must not start with

  • http:// or https://
  • http://www. or https://www.

I've managed to understand this part of the regex which correspond with the first criteria :

/.*(\.com|\.net)$/

But i have no idea how to achieve the 2 others conditions to make an unique regex.

Thanks for your help.

解决方案

A regex solution is easy. Simply assert a negative lookahead at the start of the string like so: (With comments...)

if (preg_match('%
    # Match non-http ,com or .net domain.
    ^             # Anchor to start of string.
    (?!           # Assert that this URL is NOT...
      https?://   # HTTP or HTTPS scheme with
      (?:www\.)?  # optional www. subdomain.
    )             # End negative lookahead.
    .*            # Match up to TLD.
    \.            # Last literal dot before TLD.
    (?:           # Group for TLD alternatives.
      net         # Either .net
    | com         # or .com.
    )             # End group of TLD alts.
    $             # Anchor to end of string.
    %xi', $text)) {
    // It matches.
} else {
    // It doesn't match.
}

Note that since: http://www. is a subset of: http://, the expression for the optional www. is not necessary. Here is a shorter version:

if (preg_match('%^(?!https?://).*\.(?:net|com)$%i', $text)) {
    // It matches.
} else {
    // It doesn't match.
}

Simple regex to the rescue!

这篇关于简单的域名正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆