我知道有很多用于 URL 等的 RegEx,但我真的很困惑为什么这个不起作用。我正在尝试确保用户输入的是正确的网站,允许使用 www 或不使用 www。
var pattern =
/http(s?):\/\/ (http:// or https://)
(?:[a-zA-Z]+\.){0,1} (0 or 1 instance of www)
(?:[a-zA-Z0-9][a-zA-Z0-9-]+){1} (1 instance of a domain name)
(?:\.[a-zA-Z]{2,6})+/; (1 or more instance of .com or .co.uk)
它适用于以下使用 pattern.test() 的测试用例
- > http://www.stackoverflow.com -> 是的
- > http://stackoverflow.com -> 是的
- > https://stackoverflow.com -> 是的
- htts://stackoverflow.com -> false
- http://stackoverflow.com -> false
然而,即使我明确告诉正则表达式它必须匹配 .com 或 .co.uk 等,它允许我写这样的废话:
- > http://www.stackoverflow -> 正确(错误)
- > http://www.stackoverflow . -> 正确(错误)
- > http://www.stackoverflow.c -> 正确(错误)
我一直在绞尽脑汁尝试不同的组合,但我能理解为什么即使我明确表示必须有一个或多个域扩展,但那部分似乎并不重要?
干杯
最佳答案
如果您尝试验证一个字符串,您需要将它锚定到字符串的开头和结尾:
var pattern =
/<b>^</b>http(s?):\/\/ (http:// or https://)
(?:[a-zA-Z]+\.){0,1} (0 or 1 instance of www)
(?:[a-zA-Z0-9][a-zA-Z0-9-]+){1} (1 instance of a domain name)
(?:\.[a-zA-Z]{2,6})+<b>$</b>/; (1 or more instance of .com or .co.uk)
对于 www.stackoverflow
,第一组不匹配(因为你说它是可选的),然后第二组匹配 www
,第三组是匹配 .stacko
.
提示:
{1}
不是必需的{0,1}
等同于?
- 由于您没有使用任何捕获,
(s?)
可能只是s?
关于javascript - JavaScript 中的主机名 url 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18689550/