Remove HTML tags from a String

后端 未结 30 3785
误落风尘
误落风尘 2020-11-21 07:35

Is there a good way to remove HTML from a Java string? A simple regex like

replaceAll("\\\\<.*?>", &quo         


        
30条回答
  •  [愿得一人]
    2020-11-21 08:05

    If the user enters hey!, do you want to display hey! or hey!? If the first, escape less-thans, and html-encode ampersands (and optionally quotes) and you're fine. A modification to your code to implement the second option would be:

    replaceAll("\\<[^>]*>","")
    

    but you will run into issues if the user enters something malformed, like .

    You can also check out JTidy which will parse "dirty" html input, and should give you a way to remove the tags, keeping the text.

    The problem with trying to strip html is that browsers have very lenient parsers, more lenient than any library you can find will, so even if you do your best to strip all tags (using the replace method above, a DOM library, or JTidy), you will still need to make sure to encode any remaining HTML special characters to keep your output safe.

提交回复
热议问题