有一些网站中存在不能复制的文本,这种时候就只能用F12开发者工具来复制源代码,源代码中总是存在着html标签,自己很难去掉,所以我写了这个代码,跟大家一起交流
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HTMLSpirit{
public static String delHTMLTag(String htmlStr){
String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式
Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
Matcher m_script=p_script.matcher(htmlStr);
htmlStr=m_script.replaceAll(""); //过滤script标签
Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
Matcher m_style=p_style.matcher(htmlStr);
htmlStr=m_style.replaceAll(""); //过滤style标签
Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
Matcher m_html=p_html.matcher(htmlStr);
htmlStr=m_html.replaceAll(""); //过滤html标签
return htmlStr.trim(); //返回文本字符串
}
/**
* 去掉字符串里面的html代码。<br>
* @param content
* 内容
* @return 去掉后的内容
*/
public static String stripHtml(String content) {
// <p>段落替换为换行
content = content.replaceAll("<p .*?>", "\r\n");
// <br><br/>替换为换行
content = content.replaceAll("<br\\s*/?>", "\r\n");
// 去掉其它的<>之间的东西
content = content.replaceAll("\\<.*?>", "");
// 还原HTML
// content = HTMLDecoder.decode(content);
return content;
}
}
上面这段代码是我参考网上的代码写的,用来去掉文本中的HTML标签,传入的是字符串,然后我又写了一个测试类用io流来读取文件,输出文件
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("E:\\text.txt");
// 读取文件,并且以utf-8的形式写出去
BufferedReader bufread;
String read;
bufread = new BufferedReader(new FileReader(file));
while ((read = bufread.readLine()) != null) {
System.out.println(read);
HTMLSpirit html = new HTMLSpirit();
//换行
read=html.delHTMLTag(read);
//去html标签
read=html.stripHtml(read);
//创建一个FileWriter对象
FileWriter fw = new FileWriter("D:\\1.txt",true);
BufferedWriter bufw=new BufferedWriter(fw);
//调用write的方法将字符串写到流中
bufw.write(read);
bufw.flush();
bufw.close();
fw.close();
System.out.println("输出完毕!输出路径为:D:\\1.txt");
}
bufread.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
这段代码读取的是E盘下test.txt文件,输出到D盘1.txt文件,这些都可以更换!
1139

被折叠的 条评论
为什么被折叠?



