我有下面的代碼應該從部分字符串中刪除所有的HTML,這是由美元符號引用(可能更多)。這工作正常,但我也需要保留這些美元符號。任何建議,謝謝從只有一部分字符串中刪除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$"
HTML匹配不應使用正則表達式來完成。 – 2012-07-19 18:50:25
請你提供一個輸入/輸出的例子。 – Chris911 2012-07-19 18:51:17
我知道,但REGEX是擺脫它的最簡單的方法。我不需要做任何事情... – MartinM 2012-07-19 18:52:10