Java to get rid of all the tags in the HTML two ways-open-source jar and write their own regular expressions

Source: Internet
Author: User

Java removes all the tags in the HTML, mainly two, either with open-source jars or write regular expressions on their own. If you write yourself, you may not be able to handle some of your custom tags. Enterprise application is basically able to find open source to find open source, really do not write their own ...

1, open source, what I have found is the Jsoup package:

     Public Staticstring Gettextfromthml (String htmlstr) {Document doc=Jsoup.parse (HTMLSTR); String text=Doc.text (); //Remove extra white spaceStringBuilder Builder =NewStringBuilder (text); intindex = 0;  while(Builder.length () >index) {            CharTMP =Builder.charat (index); if(Character.isspacechar (tmp) | |character.iswhitespace (TMP)) {Builder.setcharat (index,‘ ‘); } Index++; } text= Builder.tostring (). ReplaceAll ("+", ""). Trim (); returntext; }

2, write their own words, Baidu a lot of search, here just borrow:

 Public Staticstring Removetag (String htmlstr) {string Regex_script= "<script[^>]*?>[\\s\\S]*?<\\/script>";//ScriptString Regex_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";//styleString regex_html = "<[^>]+>";//HTML TagString regex_space = "\\s+|\t|\r|\n";//Other charactersPattern P_script=pattern.compile (Regex_script, pattern.case_insensitive); Matcher M_script=P_script.matcher (HTMLSTR); Htmlstr= M_script.replaceall (""); Pattern P_style=Pattern. Compile (Regex_style, pattern.case_insensitive); Matcher M_style=P_style.matcher (HTMLSTR); Htmlstr= M_style.replaceall (""); Pattern p_html=pattern.compile (regex_html, pattern.case_insensitive); Matcher m_html=P_html.matcher (HTMLSTR); Htmlstr= M_html.replaceall (""); Pattern P_space=Pattern. Compile (Regex_space, pattern.case_insensitive); Matcher M_space=P_space.matcher (HTMLSTR); Htmlstr= M_space.replaceall (""); returnHtmlstr; }

Java to get rid of all the tags in the HTML two ways-open-source jar and write their own regular expressions

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.