我需要从字符串中去除一些无效字符,并编写了 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”如果我从包含相同字符串的文件中读取。
我的问题是:
- 为什么我会出现这种行为?
- 如何更改我的代码以在所有情况下都正确地删除\u003c?
谢谢
最佳答案
hello \u003c here < and > there
ASCII 文件中的 \u003c
不会这样做,您需要将实际的 Unicode 字符放入 Unicode 编码的文本文件中。
关于java - 逃避角色的艰难时光,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3711529/