【发布时间】:2010-09-14 17:51:14
【问题描述】:
我需要从字符串中去除一些无效字符,并编写了 StringUtil 库的以下代码部分:
public static String removeBlockedCharacters(String data) {
if (data==null) {
return data;
}
return data.replaceAll("(?i)[<|>|\u003C|\u003E]", "");
}
我有一个包含一行的测试文件非法字符.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?
谢谢
【问题讨论】:
标签: java regex escaping character