2013-10-04 46 views
0

我有一個簡單的問題,我需要從Java中的HTML字符串中刪除所有感嘆號。 我試着Java刪除所有感嘆號

testo = testo.replaceAll("\\\\!", "! <br>"); 

regex = "\\s*\\b!\\b\\s*"; 
     testo = testo.replaceFirst(regex, "<br>"); 

testo = testo.replaceAll("\\\\!", "! <br>"); 

但不起作用。有人能幫我嗎? 另一個小問題,我需要用單個分隔線替換1,2或3個感嘆號 謝謝大家!

+2

什麼是逃避'!'的? :>無論如何,考慮'replaceAll(「!+」,「!
」)' – user2246674

+0

謝謝!這行得通!不知道這個轉義 – Lele

+1

'!'在正則表達式語法中並不特殊(本身)。 「+」表示「匹配一次或多次」。如果您只希望*匹配* 3次,請參閱傑裏的回答(我以前的評論將連續匹配儘可能多的「!」,例如:1,4,或5000次)。 – user2246674

回答

2

爲什麼你需要這個正則表達式?你可以簡單地做String#replace

testo = testo.replace("!", "! <br>"); 

但是刪除多個感嘆號使用:

testo = testo.replaceAll("!+", "! <br>"); 
+1

「我需要用單個分隔符替換1,2或3個感嘆號」 – user2246674

+0

謝謝,解決方法在評論中 – Lele

2

你沒有逃跑的感嘆號:

testo = testo.replaceAll("!{1,3}", "! <br>"); 

應該做的。

{1,3}表示連續出現1至3次。