2010-08-10 107 views
0

可能重复:
Extract text and links from HTML using Regular Expressions正则表达式从HTML中提取链接

给出一个包含HTML,如字符串:

 <td scope="row">1</td> 
     <td scope="row"></td> 
     <td scope="row"><a href="/Archives/directory.htm">directoryfile.htm</a></td> 
     <td scope="row">directoryfile</td> 
     <td scope="row">104569</td> 
    </tr> 
    <tr class="blueRow"> 
     <td scope="row">2</td> 
     <td scope="row"></td> 
     <td scope="row"><a href="/Archives/historicaldata.htm</a></td> 
     <td scope="row">historicaldata</td> 
     <td scope="row">40361</td> 
    </tr> 
    <tr> 
     <td scope="row">&nbsp;</td> 
     <td scope="row"><span class="blue">Complete submission text file</span></td> 
     <td scope="row"><a href="/Archives/businessagenda.txt</a></td> 
     <td scope="row">businessagenda;</td> 
     <td scope="row">146701</td> 

我只想抓住历史的链接使用正则表达式的aldata。但是,似乎我的程序没有找到链接,并且我没有看到问题,因为正则表达式在测试仪上工作。你们可以看看有什么问题吗?

我明白正则表达式不是使用HTML的最好的东西,但我只是想尝试一下。感谢大家!

模式数据= Pattern.compile(“Archives。* \ s。* historicaldata”);
Matcher test1 = data.matcher(inputHTML); (test1.find()){

while(test1.find()){
System.out.println(“Test:Now matching”); //不打印
}

+4

鸭,在“ARRGGH!用正则表达式解析Html!”之前!人群向你投掷一只鞋。 – 2010-08-10 19:38:13

+1

太迟了,[鞋子已被抛出](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – NullUserException 2010-08-10 19:43:46

+2

我会看到你的“用正则表达式解析html”,并提出你“用于布局的表格”,“为颜色命名的css类”和“.htm而不是用文件名中的.html” – 2010-08-10 19:46:18

回答

0

如果你只是想匹配的“档案\ historicaldata”,那么你的正则表达式的字符串应该是事实上 "Archives\/historicaldata"您可以使用"Archives/historicaldata"

0

在你图案"Archives.*\s.*historicaldata"

Pattern data = Pattern.compile("Archives.*\s.*historicaldata"); 

\s装置空格[1],并且由于不存在空白在"/Archives/directory.htm"它不匹配。尽量只

Pattern data = Pattern.compile("Archives.*historicaldata"); 

[1]“\ S”是不正确也 - 让在你必须转义反斜线,因此成为模式。“档案* \ S * historicaldata”