How do I use a regular expression from Java to extract an HTML tag?

Source: Internet
Author: User


Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

public class Test {

public static void Main (String args[]) {
String html = "<title>abcd</title>gsdggas<title></title>jkll<title>005</title > ";
Simple example, equivalent to String html=gethtml (string urlstring);
List resultlist = getcontext (HTML);
for (Iterator iterator = Resultlist.iterator (); Iterator.hasnext ();) {
String context = (string) iterator.next ();
SYSTEM.OUT.PRINTLN (context);
}
}

/**
* Extract the text XXXX in "<title>XXXX</title>"
* @param HTML document content to parse
* @return Resolution results, can be multiple matches, each matching results in the document appear in order to add in the results list
*/
public static List GetContext (String html) {
List resultlist = new ArrayList ();
Pattern p = pattern.compile ("<title> ([^</title>]*)");//matching document at end of <title> beginning,</title>
Matcher m = p.matcher (HTML);//Start compiling
while (M.find ()) {
Resultlist.add (M.group (1));//Get the matched part
}
return resultlist;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.