Extraction of string from particular tag using java

Viewed 80

I am having few tags inside of html. As you can see in below HTML having <AT></AT>. So I need to extract text from <AT></AT> this tag.

I have followed below approach

  1. Written one regex what will extract text from AT tag

Below is testing string::

href="<AT>EXTRACT_URL</AT>" target="_blank" style="font-weight: bold;letter-spacing: normal;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Sign In</a></td></tr></tbody></table></td></tr> <a href="<AT>EXTRACT_URL</AT>" target="_blank" title="" class="" target="_blank"> <a href="<AT>EXTRACT_URL</AT>" target="_blank" title="" class="" target="_blank"> <a href="<AT>EXTRACT_URL</AT>" target="_blank" title="" class="" target="_blank">

Used below program for extracting text from AT Tag

private static final Pattern TAG_REGEX = Pattern.compile("<AT>(.*)</AT>");

public static String getText(String text) {
    final Matcher matcher = TAG_REGEX.matcher(text);

    while (matcher.find()) {
        String url = matcher.group(1);
        
        System.out.println("Extracted URL::"+url);                      
    }   
}

Getting output from above program:

Extracted URL::EXTRACT_URL</AT>" target="_blank" style="font-weight: bold;letter-spacing: normal;line-height: 100%;text-align: center;text-decoration: none;color: #FFFFFF;">Sign In</a></td></tr></tbody></table></td></tr> <a href="<AT>EXTRACT_URL</AT>" target="_blank" title="" class="" target="_blank"> <a href="<AT>EXTRACT_URL</AT>" target="_blank" title="" class="" target="_blank"> <a href="<AT>EXTRACT_URL

Expected Output:

Extracted URL::EXTRACT_URL
Extracted URL::EXTRACT_URL
Extracted URL::EXTRACT_URL
Extracted URL::EXTRACT_URL

Why I am not getting expected output?

1 Answers

It's because of the Pattern

Correct patter in this case would be

private static final Pattern TAG_REGEX = Pattern.compile("<AT>(.*?)</AT>");

Both will match any sequence of characters but

  • .* is greedy and will match as much as possible (it will end at the last </AT>)
  • .*? is reluctant and will match as few as possible

More at this tutorial

Related