2014-02-10 24 views
1

我用Pattern作爲replaceAll方法中的參數,我想刪除打開和關閉括號(包括括號字符)內的所有字符,但只有在字符內刪除,括號仍然存在。下面是我的Java代碼如何使用字符串中的模式replaceAll

String test = "This is my test (inside the brackets) and finish here"; 
String regex = "\\(.*\\)"; 

Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(test); 
String out = test.replaceAll(matcher.group(), ""); 
System.out.println(out); 

輸出This is my test() and finish here.

回答

3

不同,需要使用Matcher#replaceAll一個Pattern使用它沒有String#replaceAll

String test = "This is my test (inside the brackets) and finish here"; 
String regex = "(?<=\\().*?(?=\\))"; 

Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(test); 
String out = matcher.replaceAll(""); 
System.out.println(out); 
//=> This is my test() and finish here 

PS:您也需要一個變化你的輸出是正則表達式。

+0

我很確定他也想擺脫括號。查看我的回答,瞭解我的想法。 –

+0

我想在同一行,然後在問題中看到這個:'輸出是這是我的測試()並在這裏完成。「# – anubhava

0

嘗試,

String test = "This is my test (inside the brackets) and finish here"; 
System.out.println(test.replaceAll("\\(.*\\)", "")); 

String.replaceAll()第一個參數是一個正則表達式

+0

其實,我想自動構建正則表達式,所以我不能把它作爲參數 –

1

你不能越來越從代碼的結果。如果您不在匹配器上撥打find(),則撥打group()時會發生異常。但是,如果您做了請先撥打find()group()將返回字符串(inside the brackets),這將被視爲正則表達式,這意味着括號將被視爲元字符。所以它將匹配inside the brackets(包括前導和尾隨空格,但不包括括號)。這將解釋你的輸出。

修復方法是致電matcher.replaceAll("")而不是test.replaceAll(matcher.group(), "")。並且不要打電話matcher.find()。 ;)

相關問題