是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
当前回答
〇应该可以
使用这个
text.replaceAll('<.*?>' , " ") -> This will replace all the html tags with a space.
这
text.replaceAll('&.*?;' , "")-> this will replace all the tags which starts with "&" and ends with ";" like , &, > etc.
其他回答
如果你是为Android编写程序,你可以这样做……
androidx.core.text.HtmlCompat.fromHtml(指令,HtmlCompat.FROM_HTML_MODE_LEGACY) .toString ()
听起来好像您想从HTML转换为纯文本。 如果是这样的话,请查看www.htmlparser.org。下面是一个示例,它从URL中找到的html文件中剥离所有标记。 它使用org.htmlparser.beans.StringBean。
static public String getUrlContentsAsText(String url) {
String content = "";
StringBean stringBean = new StringBean();
stringBean.setURL(url);
content = stringBean.getStrings();
return content;
}
从字符串中删除HTML标签。在某个地方,我们需要解析一些字符串,这些字符串是由服务器端的Httpresponse等响应接收到的。
所以我们需要解析它。
在这里,我将展示如何从字符串中删除html标签。
// sample text with tags
string str = "<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>";
// regex which match tags
System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");
// replace all matches with empty strin
str = rx.Replace(str, "");
//now str contains string without html tags
我知道这是旧的,但我只是在一个项目,需要我过滤HTML,这工作得很好:
noHTMLString.replaceAll("\\&.*?\\;", "");
而不是这样:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
您可能希望在剥离HTML之前将<br/>和</p>标记替换为换行符,以防止它像Tim建议的那样变得难以识别。
我能想到的唯一方法是删除HTML标记,但在尖括号之间留下非HTML标记,将检查HTML标记列表。沿着这条线……
replaceAll("\\<[\s]*tag[^>]*>","")
然后html解码特殊字符,如&结果不应该被认为是消毒的。