首先是兩個正則表達式:
1.<[^>]+>:這個正則表達式可以匹配所有html標簽,可以100%匹配(註意頁面編碼方式和讀取的編碼方式)。
2.>[^<]+<:這個可以匹配標簽內容,本人對正則不是很熟悉,因而隻是簡單的將第一個正則表達式反瞭過來,匹配出來的結果都會帶著><,如果有更好的正則表達式,希望可以告訴我。
下面上程序:
[java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class URLTest {
/**
* @param args
* @throws URISyntaxException
*/
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.ascii-code.com/");
InputStreamReader reader = new InputStreamReader(url.openStream());
BufferedReader br = new BufferedReader(reader);
String s = null;
while((s=br.readLine())!=null){
s = GetLabel(s);
if(s!=null){
System.out.println(s);
}
}
br.close();
reader.close();
}
public static String GetContent(String html) {
//String html = "<ul><li>1.hehe</li><li>2.hi</li><li>3.hei</li></ul>";
String ss = ">[^<]+<";
String temp = null;
Pattern pa = Pattern.compile(ss);
Matcher ma = null;
ma = pa.matcher(html);
String result = null;
while(ma.find()){
temp = ma.group();
if(temp!=null){
if(temp.startsWith(">")){
temp = temp.substring(1);
}
if(temp.endsWith("<")){
temp = temp.substring(0, temp.length()-1);
}
if(!temp.equalsIgnoreCase("")){
if(result==null){
result = temp;
}
else{
result+="____"+temp;
}
}
}
}
return result;
}
public static String GetLabel(String html) {
//String html = "<ul><li>1.hehe</li><li>2.hi</li><li>3.hei</li></ul>";
String ss = "<[^>]+>";
String temp = null;
Pattern pa = Pattern.compile(ss);
Matcher ma = null;
ma = pa.matcher(html);
String result = null;
while(ma.find()){
temp = ma.group();
if(temp!=null){
if(temp.startsWith(">")){
temp = temp.substring(1);
}
if(temp.endsWith("<")){
temp = temp.substring(0, temp.length()-1);
}
if(!temp.equalsIgnoreCase("")){
if(result==null){
result = temp;
}
else{
result+="____"+temp;
}
}
}
}
return result;
}
}
GetContent用來獲取標簽內容。
GetLabel用來獲取標簽。