简体   繁体   English

使用JSoup仅除去HTML标签,而不除去'<'和'>'标签内的数据

[英]Using JSoup to remove only HTML tags and not data within '<' and '>' tags

I'm using JSoup to parse string which contains HTML tags to plain text. 我正在使用JSoup解析包含HTML标记为纯文本的字符串。 For example: 例如:

String newStr = Jsoup.parse(testStrHTML).text();

It is parsing it very well but problem is if my Java string contains a data between < and > for eg Hello <test@gmail.com> so it is removing email address data. 它的解析效果很好,但是问题是我的Java字符串是否包含<>之间的数据(例如Hello <test@gmail.com>因此它正在删除电子邮件地址数据。 Output I'm getting is Hello , where I'm expecting Hello <test@gmail.com> . 我得到的输出是Hello ,我期望在其中Hello <test@gmail.com>

I have tried it with regular expression as well like 我也尝试过使用正则表达式

String newStr = testStrHTML.replaceAll("\\<.*?\\>", "");

But still problem. 但是仍然有问题。

Is there anyway to parse HTML tags without custom data between < and > 无论如何在<>之间解析没有自定义数据的HTML标签

Your regexp 您的正则表达式

String newStr = testStrHTML.replaceAll("\\<.*?\\>", "");

Completly removes the tag. 完全删除标签。 It matches the start of the < at the beginning of the tag, the label of the tags, any attributes of the tag and the final >. 它与<的开头,标签的开头,标签的标签,标签的所有属性以及最后的>匹配。 It then replaces this with an empty string. 然后将其替换为空字符串。

String newStr = testStrHTML.replaceAll("\\<.([^>]*)\\>", "\\1");

Should replace all tags with the label and any attributes of the tag. 应将所有标签替换为标签和标签的所有属性。 This roughly matches the same as your regexp, but it replaces the match with the text within the brackets. 这与您的regexp大致匹配,但是用括号内的文本替换了匹配项。

Note that this removes context so it might not be a good solution. 请注意,这会删除上下文,因此它可能不是一个好的解决方案。 It also doesn't produce easily readable output because valid html is partially retained. 由于有效的html被部分保留,因此它也不会产生易于阅读的输出。

It might be better to stay with Jsoup and navigate the DOM. 最好还是使用Jsoup并浏览DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM