java从网页或文本中提取网址URL(使用正则表达式)

提取网址(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结果如下图:

java提取网址URL结果图

功能备注:

如果内容中含有邮箱的话,会提取到最后的域名地址。所以用户可以自行调整不提取不带前缀的网址,或者提取之后,想必你是要替换为空或者其它字符,可以判断该文本前是不是为“@”字符,进而决定是不是要替换。

草木全
分享到:
另外请注意:image标签或视频、音频类的标签、地图等含有网址,也会匹配到,如果要替换请判断前面的属性。

共1条回复

草木全 如果是这些网址就是引用本站的数据,则可以直接将本站的域名不替换。 「6年前」
0
共 1 条   当前1/1页

© 2014 究问社区 copyRight 豫ICP备13003319号-1