删除两个字符之间的子字符串(java)

时间:2012-05-05 13:12:52

标签: java regex string substring

我有一个java字符串,如:

String string = "I <strong>really</strong> want to get rid of the strong-tags!";

我想删除标签。我有一些标签更长的其他字符串,所以我想找到一种方法来删除“&lt;&gt;”之间的所有内容字符,包括那些字符。

一种方法是使用内置字符串方法将字符串与regEx进行比较,但我不知道如何编写它们。

2 个答案:

答案 0 :(得分:17)

在使用正则表达式解析HTML时(由于其允许的复杂性),建议小心,但对于“简单”HTML和简单文本(文本中没有文字<>),这将起作用:

String stripped = html.replaceAll("<.*?>", "");

答案 1 :(得分:0)

避免使用正则表达式:

String toRemove = StringUtils.substringBetween(string, "<", ">");
String result = StringUtils.remove(string, "<" + toRemove + ">"); 

对于多个实例:

String[] allToRemove = StringUtils.substringsBetween(string, "<", ">");
String result = string;
for (String toRemove : allToRemove) {
  result = StringUtils.remove(result, "<" + toRemove + ">"); 
}
  

Apache StringUtils函数为null,empty和没有匹配安全性