我有以下代码应该从字符串的一部分中删除所有 HTML,该字符串由美元符号引用(可能更多)。这很好用,但我还需要保留那些美元符号。任何建议,谢谢
private static String removeMarkupBetweenDollars(String input){
if ((input.length()-input.replaceAll("\\$","").length())%2!=0)
{
throw new RuntimeException("Missing or extra: dollar");
}
Pattern pattern = Pattern.compile("\\$(.*?)\\$",Pattern.DOTALL);
Matcher matcher = pattern.matcher(input);
StringBuffer sb =new StringBuffer();
while(matcher.find())
{ //prepending does NOT work, if sth. is in front of first dollar
matcher.appendReplacement(sb,matcher.group(1).replaceAll("\\<.*?\\>", ""));
sb.append("$"); //note this manual appending
}
matcher.appendTail(sb);
System.out.println(sb.toString());
return sb.toString();
}
感谢帮助!
String input="<p>$<em>something</em>$</p> <p>anything else</p>";
String output="<p>$something$</p> <p>anything else</p>";
更复杂的输入输出:
String input="<p>$ bar <b>foo</b> bar <span style=\"text-decoration: underline;\">foo</span> $</p><p>another foos</p> $ foo bar <em>bar</em>$";
String output="<p>$ bar foo bar foo $</p><p>another foos</p> $ foo bar bar$"