2013-08-31 24 views
1

我有一個字符串,我想擺脫括號爲什麼的replaceAll拋出一個異常

這是我的字符串"(name)" 的,我想"name"

同樣的事情,沒有括號

我有String s = "(name)";

我寫

s = s.replaceAll("(",""); 
s = s.replaceAll(")",""); 

,我獲取該

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 
(

我如何擺脫支架的異常?在這裏不需要

回答

7

括號字符()限定一個capturing group的邊界,其中被用作replaceAll第一個參數正則表達式。字符需要被轉義。

s = s.replaceAll("\\(",""); 
s = s.replaceAll("\\)",""); 

更重要的是,你可以簡單地將括號中character class防止字符被解釋爲元字符

s = s.replaceAll("[()]",""); 
+0

奇怪的是我點擊約10倍於這個答案之前,它讓我接受它.. –

+0

需要它至少要等15分鐘到接受'SO' – Reimeus

+0

是奇數的答案..這是爲什麼? –

4

s = s.replace("(", "").replace(")", "");

正則表達式。

如果你想使用正則表達式(不知道爲什麼你會)你可以做這樣的事情:

s = s.replaceAll("\\(", "").replaceAll("\\)", "");

問題是()是元字符,所以你需要轉義(假設你希望將它們解釋爲它們的顯示方式)。

2

String#replaceAll需要正則表達式作爲參數。 您正在使用Grouping Meta-characters作爲正則表達式參數。這就是獲取錯誤的原因。

元字符用於對圖案進行分組,劃分和執行特殊操作。

 
\  Escape the next meta-character (it becomes a normal/literal character) 
^  Match the beginning of the line 
.  Match any character (except newline) 
$  Match the end of the line (or before newline at the end) 
|  Alternation (‘or’ statement) 
()  Grouping 
[]  Custom character class 

所以使用
1. \\(代替(
2. \\),而不是)

1

你需要逃避(和)他們有特殊的字符串字面含義。 像這樣做:

s = s.replaceAll("\\(",""); 
s = s.replaceAll("\\)",""); 
+0

它不會自行修改,它會創建一個新的'String'。 –

+0

是嗎?讓我檢查一下。 – tom

+0

是的,是的。 –

2

你需要逃避這樣括號:

s = s.replaceAll("\\(",""); 
s = s.replaceAll("\\)",""); 

你需要兩條斜線,因爲正則表達式處理引擎需要看到一個\(處理支架作爲一個字面括號(而不是正則表達式的一部分),並且您需要將反斜槓轉義,以便正則表達式引擎能夠將其視爲反斜槓。

1
s=s.replace("(","").replace(")",""); 
相關問題