2010-09-14 13 views
1

我需要從一個字符串去掉一些無效字符,寫了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?

感謝

回答

3

當您編譯源文件,這種情況發生的第一件事 - 任何詞法或對其進行解析之前 - 就是Unicode轉義,\u003C\u003E,轉換爲實際字符,<>。所以,你的代碼是真的:

return data.replaceAll("(?i)[<|>|<|>]", ""); 

當你編譯針對字符串文字測試的代碼,同樣的事情發生;您寫的測試字符串爲:

"a <b> c\u003e\u003E\u003c\u003C" 

...是真的:

"a <b> c>><<" 

但是,當您從文件中讀取測試字符串時,不會發生此類轉換;您最終試圖將六個字符的序列\u003c與單個字符<相匹配。如果你真的想匹配\u003C\u003E,你的代碼應該是這樣的:

return data.replaceAll("(?i)(?:<|>|\\\\u003C|\\\\u003E)", ""); 
  • 如果使用一個反斜槓,Java編譯器將其解釋爲Unicode轉義並將其轉換爲<>

  • 如果使用反斜槓,該正則表達式編譯器將其解釋爲Unicode轉義,認爲要比賽一個<>

  • 如果使用3個反斜槓,Java編譯器把它變成\<\>,正則表達式編譯器會忽略反斜槓,它試圖匹配<>

  • 所以,以匹配原始的Unicode轉義序列,你必須使用反斜槓以匹配轉義序列一個反斜槓。

請注意,我也更改了括號。 [<|>]是與<,|>匹配的character class;你想要的是一個alternation

+0

謝謝大家:解釋,捕捉我對括號的錯誤,並提供我正在尋找的修復。 – double07 2010-09-15 15:59:05

5

你好\ u003c這裏<和>有

在ASCII文件不會做的\u003c,你需要把實際的Unicode字符在Unicode編碼的文本文件。

0

在我看來,問題不在於你的逃跑,但事實上,你有unicode數據,你試圖解析。

您是否嘗試過使用readFileToString的兩個參數版本,用readFileToString(File, Encoding)替換您的readFileToString(File)調用?

資源