2017-10-04 28 views
0

我嘗試了不同的解決方案有很多變種,這裏解釋使用Java Regex,如何在括號之前和之後添加空格?

How to add space on both sides of a string in Java

Regex add space between all punctuation

Add space after capital letter

以及其他那些關於括號(還有更多)

Regex to match parenthesis

我有一個字符串,我只是想這樣的:喜()

要成爲這樣的:喜()

我迄今爲止嘗試:

if (phrase.matches("^.*[(].*$")){ 
      phrase.replaceAll("\\(", " \\("); 
     } 

的,如果工作正常,但在的replaceAll沒有做任何事情。

我在線閱讀,我可能需要把先前的值在的replaceAll所以我嘗試以下

if (phrase.matches("^.*[(].*$")){ 
    phrase.replaceAll("(.*)\\(", " \\("); 
} 

除了這

if (phrase.matches("^.*[(].*$")){ 
    phrase.replaceAll("(.*)\\(", "(.*) \\("); 
} 

if (phrase.matches("^.*[(].*$")){ 
     phrase.replaceAll("(.*)\\((.*)", "(.*) \\((.*)"); 
    } 

在這一點上,我覺得我只是嘗試隨機的東西,我在這裏錯過了一些微不足道的東西。

+0

[見此](https://regex101.com/r/TSv6V1/2)。正則表達式:''('; Replace'('' – ctwheels

+0

)單個反斜槓在Java中不起作用,相當於\\或\'或\「,我全部嘗試了它們 – Maude

+0

從上面的鏈接可以看到,選擇java,你會得到這個頁面:https://regex101.com/r/TSv6V1/2/codegen?language=java。我在上面發佈的評論是純正規表達式,你需要轉義字符之後在Java中(正如本評論中的鏈接所示) – ctwheels

回答

1

replaceAll不改變字符串。嘗試

if (phrase.matches("^.*[(].*$")){ 
    System.out.println(phrase.replaceAll("\\(", " \\(")); 
    // => f () 
} 

if (phrase.matches("^.*[(].*$")){ 
    phrase = phrase.replaceAll("\\(", " \\(")); 
} 
0

在java中,字符串是不可變的。所以你可能想把replaceAll結果賦給一個變量。

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

而且你如果可以省略條件,導致replaceAll將取代琴絃,只有當它找到一個匹配。

相關問題