提取网址(URL)示例如下:
http://www.ijiuwen.com | https://www.baidu.com | www.ijiuwen.com | baidu.com
http://www.baidu.com/xxx.html等格式
java提取代码如下:
public class WangGot { public static void main(String[] args) throws Exception { String content = MyUtils.read("F:\\第七届西部锅炉展电子版会刊.txt"); //只提取http://或https://开头的 /*Pattern p = Pattern.compile("(?<!\\d)(?:(?:[a-zA-z]+://[^\\s|^\\u4e00-\\u9fa5]*))(?!\\d)"); Matcher m = p.matcher(content); while (m.find()) { System.out.println(m.group()); }*/ Pattern pb = Pattern.compile("(?<!\\d)(?:(?:[\\w[.-://]]*\\.[com|cn|net|tv|gov|org|biz|cc|uk|jp|edu]+[^\\s|^\\u4e00-\\u9fa5]*))"); Matcher mb = pb.matcher(content); while (mb.find()) { //mb.replaceAll(""); System.out.println(mb.group()); } } }使用到的文件为: java提取网址示例文件
使用到的工具MyUtils.java代码如下:
package com.guoluyun.test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Random; public class MyUtils { public static String random(){ StringBuffer sb=new StringBuffer(); int times=new Random().nextInt(5)+3; for(int i=0;i<times;i++){ sb.append("<p>").append(new Random().nextLong()); sb.append(MD5.MD5Encode(sb.toString())).append("</p>"); } return "<div style='display:none'>"+sb.toString()+"</div>"; } /** * 读取文件内容 * * @param fileName * 待读取的完整文件名 * @return 文件内容 * @throws IOException */ public static String read(String fileName) throws IOException { File f = new File(fileName); FileInputStream fs = new FileInputStream(f); String result = null; byte[] b = new byte[fs.available()]; fs.read(b); fs.close(); result = new String(b); return result; } }java代码提取网址URL结果如下图:
功能备注:
如果内容中含有邮箱的话,会提取到最后的域名地址。所以用户可以自行调整不提取不带前缀的网址,或者提取之后,想必你是要替换为空或者其它字符,可以判断该文本前是不是为“@”字符,进而决定是不是要替换。
共1条回复