使用正则表达式删除 <a href> 标签

10

我想从给定的HTML代码中提取纯文本。 我尝试使用正则表达式,并得到了

String target = val.replaceAll("<a.*</a>", "");

我的主要要求是我想删除在<a></a>之间的所有内容(包括链接名称)。当使用上面的代码时,所有其他内容也被删除了。

<a href="www.google.com">Google</a> This is a Google Link

<a href="www.yahoo.com">Yahoo</a> This is a Yahoo Link

这里我想删除<a></a>之间的值。 最终输出应该为

This is a Google Link This is a Yahoo Link


9
【标题】THE PONY HOME以下为翻译内容:【正文】 THE PONY HOME(小马之家)【注释】 暂无 - adeneo
这就是jQuery擅长的地方。 - Rimian
"String" 是什么意思?这是 JavaScript 吗? - ChaseMoskal
在JavaScript中,这不会更像是var clean_string = my_string.replace(/<a.*?<\/a>/i,'');吗? - ChaseMoskal
1个回答

28
使用非贪婪量词 (*?)。例如,要完全删除链接:
String target = val.replaceAll("<a.*?</a>", "");

或者用链接标签的内容替换链接本身:

String target = val.replaceAll("<a[^>]*>(.*?)</a>", "This is a $1 Link");

然而,我仍然建议使用适当的DOM操纵API。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接