JavaScript正则表达式实现URL检测并排除指定域名
检测URL但排除含"example"域名的JavaScript正则表达式
我最近写了一段JavaScript正则表达式,用来匹配所有URL,但会排除域名中包含"example"的情况,分享给大家参考:
(?<protocol>\w+s?:\/\/)?(?<subdomain>\w+\.)(?<domain>(?!example)(\w+))(?<tls>\.\w{2,4})(?<querystring>\/.*)?\S*
捕获组详解
每个捕获组的作用如下:
- protocol:匹配URL的协议部分(如http、https、ftp等),这部分为可选匹配
- subdomain:匹配任意子域名(如www、blog这类前缀)
- domain:匹配任意域名,这里通过负向预查
(?!example)实现了排除包含"example"的域名的需求 - tls:匹配顶级域名后缀,比如.com、.org、.net这类长度2-4的后缀
- querystring:匹配URL中域名之后的路径、查询参数等剩余部分,同样为可选匹配
匹配示例
❌ 不应被检测到的URL
- https://www.example.org/hello?
- http://www.example.org/hello
- https://blog.example.org/hello?
- example.org
- www.example.org
✅ 应被检测到的URL
- www.test.org
- www.www.test.org
- test.org
内容的提问来源于stack exchange,提问作者CristianCV
相关产品推荐
相关产品推荐

