[英]Extracting text in html using Java Regex
I need to extract text from html tags.我需要从 html 标签中提取文本。 I have written a code but the text is not being extracted.
我已经写了一个代码,但文本没有被提取。 Below is my code
下面是我的代码
import java.util.regex.Matcher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.regex.Pattern;
class getFontTagText{
String result = null;
public static void main(String args[]){
try{
getFontTagText text = new getFontTagText();
BufferedReader r = new BufferedReader(new FileReader("target.html"));
Pattern p = Pattern.compile("<FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"\\W|_000000\" LETTERSPACING=\"0\" KERNING=\"0\">(//AZUZZU Full Service Provision)</FONT>",Pattern.MULTILINE);
String line;
System.out.println("Came here");
while((line = r.readLine()) != null){
Matcher mat = p.matcher(line);
while(mat.find()){
System.out.println("Came here");
String st = mat.group(1);
System.out.format("'%s'\n", st);
}
}
}catch (Exception e){
System.out.println(e);
}
}
} }
and the html file is here和 html 文件在这里
<P ALIGN="LEFT">
<FONT FACE="Arial" SIZE="1" COLOR="#000000" LETTERSPACING="0" KERNING="0">ZUZZU Full Service Provision</FONT>
</P>
<P ALIGN="LEFT">
<FONT FACE="Arial" SIZE="1" COLOR="#000000" LETTERSPACING="0" KERNING="0">ü ö ä Ä Ü Ö ß</FONT>
</P>
mat.group(1) is being printed 'null' instead of text. mat.group(1) 正在打印 'null' 而不是文本。 Any help is much appreciated.
任何帮助深表感谢。
I would recommend to use jsoup.我建议使用 jsoup。 jsoup is a Java library for extracting and manipulating HTML data, using CSS, and jquery-like methods.
jsoup 是一个 Java 库,用于提取和操作 HTML 数据,使用 CSS 和类似 jquery 的方法。 In your case it could look like something like this :
在您的情况下,它可能看起来像这样:
public static void jsoup() throws IOException{
File input = new File("C:\\users\\uzochi\\desktop\\html.html");
Document doc = Jsoup.parse(input, "UTF-8");
Elements es = doc.select("FONT");//select tag
for(Element e : es){
System.out.println(e.text());
}
}
If you prefer to use regex just match the text between > and < , for example如果您更喜欢使用正则表达式,只需匹配 > 和 < 之间的文本,例如
public static void regex(){
Pattern pat = Pattern.compile("<FONT [^>]*>(.*?)</FONT>");//
String s = "<html>\n" +
"<body>\n" +
"\n" +
"<P ALIGN=\"LEFT\">\n" +
" <FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"#000000\" LETTERSPACING=\"0\" KERNING=\"0\">ZUZZU Full Service Provision</FONT>\n" +
" </P>\n" +
" <P ALIGN=\"LEFT\">\n" +
" <FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"#000000\" LETTERSPACING=\"0\" KERNING=\"0\">ü ö ä Ä Ü Ö ß</FONT>\n" +
" </P>\n" +
"\n" +
"</body>\n" +
"</html>";
Matcher m = pat.matcher(s);
while (m.find()) {
String found = m.group(1);
System.out.println("Found : " + found);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.