java - 逃避角色的艰难时光

标签 java regex escaping character

我需要从字符串中去除一些无效字符,并编写了 StringUtil 库的以下代码部分:

public static String removeBlockedCharacters(String data) {
    if (data==null) {
      return data;
    }
    return data.replaceAll("(?i)[<|>|\u003C|\u003E]", "");
}

我有一个测试文件 illegalCharacter.txt,里面有一行:

hello \u003c here < and > there

我运行以下单元测试:

@Test
public void testBlockedCharactersRemoval() throws IOException{
    checkEquals(StringUtil.removeBlockedCharacters("a < b > c\u003e\u003E\u003c\u003C"), "a  b  c");
    log.info("Procesing from string directly: " + StringUtil.removeBlockedCharacters("hello \u003c here < and > there"));
    log.info("Procesing from file to string:  " + StringUtil.removeBlockedCharacters(FileUtils.readFileToString(new File("src/test/resources/illegalCharacters.txt"))));
}

我得到:

INFO - 2010-09-14 13:37:36,111 - TestStringUtil.testBlockedCharactersRemoval(36) | Procesing from string directly: hello  here  and  there
INFO - 2010-09-14 13:37:36,126 - TestStringUtil.testBlockedCharactersRemoval(37) | Procesing from file to string:  hello \u003c here  and  there

我很困惑:如您所见,如果我传递包含这些值的字符串但代码未能去除“\u003c”,则代码会正确去除“<”、“>”和“\u003c”如果我从包含相同字符串的文件中读取。

我的问题是:

  1. 为什么我会出现这种行为?
  2. 如何更改我的代码以在所有情况下都正确地删除\u003c?

谢谢

最佳答案

hello \u003c here < and > there

ASCII 文件中的 \u003c 不会这样做,您需要将实际的 Unicode 字符放入 Unicode 编码的文本文件中。

关于java - 逃避角色的艰难时光,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3711529/

相关文章:

写入 Access DB 时发生 Java 错误

java - 如何将日期格式转换为mysql日期格式?

Java 字符串 : Replace a string containing $ sign

windows - 在 Windows 批处理中使用 PowerShell 命令和反引号换行符

java - 如何更改二维码图像大小?

java - Hibernate 在设置父级后尝试两次保留子级

java - 在 replaceAll 调用中修改部分正则表达式

regex 允许至少一个特殊字符,一个大写,一个小写(以任何顺序)

linq - 自动生成的 sql 代码 : single backslash as an escape character is failing

javascript - 如何允许用户在 Javascript 中输入转义字符