Java通过正则表达式获取域名简单示例
Java正则表达式获取域名
由于 url.getHost()获取域名会有漏洞,会获取不完整,因此通过正则表达式获取域名,上代码:
String url = http://www.linuxidc.com/entry/4545/0/;
Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(url);
matcher.find();
System.out.println(matcher.group());//结果:linuxidc.com
如果要得到 linuxidc.com/entry/4545/0/,正则表达式最后加上 .* 即可:
String url = "http://127.0.0.1\\.testserver.cn/1.htm";
Pattern p = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv).*", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(url);
matcher.find();
System.out.println("------------------->"+matcher.group());附:java正则表达式URL匹配
思路:
1.先验证url开始部分 https:// 或 http://
2.通过((http|https)😕/)([\w-]+.)+[\w$]+ 匹配域名www.bilibili.com
3.(/[\w-?=&./]*)? 匹配 /video/BV1Eq4y1E79W?from=search&seid
public class RegExp11 {
public static void main(String[] args){
String content = "https://www.bilibili.com/video/BV1Eq4y1E79W?from=search&seid=9946545262871408175";
//思路:
// 1.先验证url开始部分 https:// 或 http://
// 2.通过((http|https)://)([\w-]+\.)+[\w$]+ 匹配域名www.bilibili.com
// 3.(\/[\w-?=&./]*)? 匹配 /video/BV1Eq4y1E79W?from=search&seid
String regStr = "^((http|https)://)([\\w-]+\\.)+[\\w$]+(\\/[\\w-?=&./]*)?$";//[.?*]表示匹配的就是本身
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
if (matcher.find()){
System.out.println("满足格式!");
}else {
System.out.println("不满足格式!");
}
}
}总结
到此这篇关于Java通过正则表达式获取域名的文章就介绍到这了,更多相关Java正则表达式获取域名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
解决Callable的对象中,用@Autowired注入别的对象失败问题
这篇文章主要介绍了解决Callable的对象中,用@Autowired注入别的对象失败问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
SpringBoot实现Server-Sent Events(SSE)的使用完整指南
使用SpringBoot实现Server-Sent Events(SSE)可以有效处理实时数据推送需求,具有单向通信、轻量级和高实时性等优势,本文详细介绍了在SpringBoot中创建SSE端点的步骤,并通过代码示例展示了客户端如何接收数据,适用于实时通知、数据展示和在线聊天等场景2024-09-09


最新评论