我想刪除所有Unicode字符和轉義字符,如(\n, \t)
等。總之,我只想要字母數字字符串。消除字符串中的Unicode字符和轉義字符
例如:
\u2029My Actual String\u2029 \nMy Actual String\n
我只想'My Actual String'
獲取。有沒有辦法做到這一點,通過使用內置的字符串方法或正則表達式?
我想刪除所有Unicode字符和轉義字符,如(\n, \t)
等。總之,我只想要字母數字字符串。消除字符串中的Unicode字符和轉義字符
例如:
\u2029My Actual String\u2029 \nMy Actual String\n
我只想'My Actual String'
獲取。有沒有辦法做到這一點,通過使用內置的字符串方法或正則表達式?
嘗試
String stg = "\u2029My Actual String\u2029 \nMy Actual String";
Pattern pat = Pattern.compile("(?!(\\\\(u|U)\\w{4}|\\s))(\\w)+");
Matcher mat = pat.matcher(stg);
String out = "";
while(mat.find()){
out+=mat.group()+" ";
}
System.out.println(out);
正則表達式匹配除unicode和轉義字符以外的所有內容。正則表達式形象地表示爲:
輸出:
My Actual String My Actual String
'\ n'或'\ t'如何在此流程中運行? –
'\ s'代表「空白字符」。再一次,這實際包含哪些字符取決於正則表達式的風格。 [\ t \ r \ n \ f]。即:'\ s'匹配空格,製表符,換行符或換頁符。 –
如果我只是想從字符串的開頭刪除所有這些字符,例如\ u2029 \\ t \\ t&* ^我的實際字符串==>我的實際字符串? –
試試這個:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.", "");
刪除轉義字符。如果你也想刪除所有其他特殊字符使用這一個:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.|[^a-zA-Z0-9\\s]", "");
(我猜你想保留空格,如果不從上面的一個取出\\s
)
感謝它爲我工作:) –
其實我也寫了RE,但它並沒有取代unicode字符,因爲在Java中'\'替換爲'\\'。 –
這被問及5分鐘前,有多大;)http://stackoverflow.com/questions/20678238/轉換 - Unicode到字符串-java –
看這裏。 http://stackoverflow.com/a/20654784/2968614 – Aditya
這只是爲'/ n',但我想爲Unicode和轉義字符其實我已完成,但在Java中'/'被替換爲'/',這就是爲什麼我的RE或功能不起作用。 –