源代码下载地址:http://www.zuidaima.com/share/1575653789993984.htm
公司有个业务需要匹配文本中的网址,度娘,谷哥了半天经常看到有对html中获取超链接的正则,只要匹配<a href=[‘"]?(.*?)[‘"]?即可,但如果是普通文本类型的则比较费事些,分享下最后的表达式:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class URLMatcher { public static void main(String[] args) { Pattern pattern = Pattern .compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*"); // 空格结束 Matcher matcher = pattern .matcher("随碟附送下载地址http://www.xxx.com/sdfsdf.htm?aaaa=%ee%sss ?sdfsyyy空格结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // 中文结束 matcher = pattern .matcher("随碟附送下载地址http://www.xxx.com/sdfsdf.htm?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // 没有http://开头 matcher = pattern .matcher("随碟附送下载地址www.xxx.com/sdfsdf.htm?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // net域名 matcher = pattern .matcher("随碟附送下载地址www.xxx.net/sdfsdf.htm?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // xxx域名 matcher = pattern .matcher("随碟附送下载地址www.xxx.xxx/sdfsdf.htm?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // yyyy域名匹配不到 System.out.println("匹配不到yyyy域名"); matcher = pattern .matcher("随碟附送下载地址www.xxx.yyyy/sdfsdf.html?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } // 没有http://www. matcher = pattern .matcher("随碟附送下载地址xxx.com/sdfsdf.html?aaaa=%ee%sss网址结束"); while (matcher.find()) { System.out.println(matcher.group(0)); } } }
结果是死的,但思路是活的,大家可以根据自己的业务随意改写表达式。
有图有真相:
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/springmvc_springdata/article/details/46873099