我需要從一個字符串去掉一些無效字符,寫了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?
感謝
謝謝大家:解釋,捕捉我對括號的錯誤,並提供我正在尋找的修復。 – double07 2010-09-15 15:59:05