难以逃脱的角色

dou*_*e07 1 java regex escaping character

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

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

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

hello \u003c here < and > there
Run Code Online (Sandbox Code Playgroud)

我运行以下单元测试:

@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"))));
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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
Run Code Online (Sandbox Code Playgroud)

我非常困惑:正如你所看到的,代码正确地删除了'<','>'和'\ u003c',如果我传递一个包含这些值的字符串,但是如果我读了就不能删除'\ u003c'来自包含相同字符串的文件.

我的问题,所以我不再失去头发,是:

  1. 为什么我会这样做?
  2. 如何在所有场合更改我的代码以正确剥离\ u003c?

谢谢

µBi*_*Bio 5

你好\ u003c在这里<和>那里

\u003c在ASCII文件不会做它,你需要把实际的Unicode字符在Unicode编码的文本文件.