开发者

Regex to extracting links from HTML [duplicate]

开发者 https://www.devze.com 2023-01-11 04:22 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Extract text and links from HTML using Regular Expressions
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Extract text and links from HTML using Regular Expressions

Given an string containing HTML such as:

       <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 t开发者_运维知识库ext file</span></td> 
        <td scope="row"><a href="/Archives/businessagenda.txt</a></td> 
        <td scope="row">businessagenda;</td> 
        <td scope="row">146701</td> 

I want to just grab the link for historicaldata using regex. However, it seems that my program is not finding the link and I do not see the problem as the regex works on the tester. Can you guys see what's the problem?

I understand that regex is not the best thing to use with HTML but I just want to try it. Thanks everyone!

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

Matcher test1= data.matcher(inputHTML);

while (test1.find()) {

System.out.println("Test: Now matching"); // Doesn't print

}


If you are just wanting to match 'Archives\historicaldata' then your regex string should be "Archives\/historicaldata" in fact you may be able to use "Archives/historicaldata"


In your pattern "Archives.*\s.*historicaldata"

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

the \s means whitespace[1], and since there is no whitespace in "/Archives/directory.htm" it doesn't match. Try just

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

[1] The "\s" is incorrect also - to get that in the pattern you have to escape the backslash so it becomes "Archives.*\s.*historicaldata"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号