我想使用Regex從html文件中提取一些文本。我正在學習正則表達式,我仍然無法理解這一切。我有提取的所有文本包括betweeen <body>
和</body>
這裏是代碼:幫助用Java和正則表達式從html標記中提取文本
public class Harn2 {
public static void main(String[] args) throws IOException{
String toMatch=readFile();
//Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?"); this one works fine
Pattern pattern=Pattern.compile(".*?<table class=\"claroTable\".*?>(.*?)</table>.*?"); //I want this one to work
Matcher matcher=pattern.matcher(toMatch);
if(matcher.matches()) {
System.out.println(matcher.group(1));
}
}
private static String readFile() {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("user.html");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read File Line By Line
while (br.readLine() != null) {
// Print the content on the console
//System.out.println (strLine);
strLine+=br.readLine();
}
//Close the input stream
in.close();
return strLine;
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
return "";
}
}
}
那麼它工作正常,像這樣的,但現在我想提取標籤之間的文本: <table class="claroTable">
和</table>
所以我更換我的正則表達式字符串".*?<table class=\"claroTable\".*?>(.*?)</table>.*?"
我也試過 ".*?<table class=\"claroTable\">(.*?)</table>.*?"
但它不起作用,我不明白爲什麼。 html文件中只有一個表格,但是在javascript代碼中出現了「table」:「... dataTables.js ...」可能是導致錯誤的原因嗎?
預先感謝您對我的幫助,
編輯:HTML文本extranct是一樣的東西:
<body>
.....
<table class="claroTable">
<td><th>some data and manya many tags </td>
.....
</table>
我想提取物<table class="claroTable">
和</table>
如果你婉t從html中提取數據:使用一個html解析器。如果你想學習RegExp:do ** not **使用html或xml輸入。遲早你會意識到,正則表達式的HTML不起作用。 –
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – NimChimpsky
@NimChimpsky我有一種感覺有人會張貼這個笑聲。 – Matt