使用正则表达式从 URL 中提取顶级和二级域 [英] Extracting top-level and second-level domain from a URL using regex

查看:23
本文介绍了使用正则表达式从 URL 中提取顶级和二级域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用正则表达式从 URL 中仅提取顶级域和二级域?我想跳过所有较低级别的域.有什么想法吗?

How can I extract only top-level and second-level domain from a URL using regex? I want to skip all lower level domains. Any ideas?

推荐答案

这是我的想法,

使用 $ 锚点从行尾匹配任何不是点的任何内容,三遍.

Match anything that isn't a dot, three times, from the end of the line using the $ anchor.

字符串末尾的最后一个匹配项应该是可选的,以允许 .com.au.co.nz 类型的域.

The last match from the end of the string should be optional to allow for .com.au or .co.nz type of domains.

last 和 second last 匹配只匹配 2-3 个字符,以免与二级域名混淆.

Both the last and second last matches will only match 2-3 characters, so that it doesn't confuse it with a second-level domain name.

正则表达式:

[^.]*.[^.]{2,3}(?:.[^.]{2,3})?$

演示:

Regex101 示例

这篇关于使用正则表达式从 URL 中提取顶级和二级域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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