替换Java中的ASCII代码和HTML标签

问题描述

不使用StringEscapeUtils怎么能达到预期的效果

public class Main {
    public static void main(String[] args) throws Exception {
      String str = "<p><b>Send FWB <br><br> &#40;if AWB has COU SHC,<br> if ticked,will send FWB&#41;</b></p>";
      str = str.replaceAll("\\<.*?\\>","");
      System.out.println("After removing HTML Tags: " + str);
    }
}

当前结果:

After removing HTML Tags: Send FWB  &#40;if AWB has COU SHC,if ticked,will send FWB&#41;

预期结果:

After removing HTML Tags: Send FWB  if AWB has COU SHC,will send FWB;

已检查: How to unescape HTML character entities in Java?


PS:这只是一个示例,输入可能会有所不同。

解决方法

您的正则表达式用于html标签<something>,而html实体将不匹配。它们的模式类似于&.*?;,您无需替换。

这应该可以解决您的麻烦

str = str.replaceAll("\\<.*?\\>|&.*?;","");

如果要在沙箱中进行试验,请尝试regxr.com并使用(\<.*?\>)|(&.*?;)括号使工具上易于识别两个不同的捕获组,并且代码中不需要。请注意,\不需要在该沙箱游乐场中转义,但是它必须在您的代码中,因为它在字符串中。