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

Replace ASCII codes and HTML tags in Java

如何在不使用 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,  if ticked , will send FWB;

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


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

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

这应该可以解决您的问题:

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

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