4 回答

TA貢獻1847條經驗 獲得超11個贊
你試過這個嗎?
str = str.replaceAll("\\({2,}", "(");
'\' 是轉義字符,因此每個特殊字符都必須以它開頭。沒有它們,正則表達式將其讀取為用于分組的左括號,并期望有一個右括號。
編輯:最初,我以為他是想恰好匹配 2

TA貢獻1712條經驗 獲得超3個贊
假設括號不需要配對,例如((((5))應該變成(5),那么下面的代碼就可以了:
str = str.replaceAll("([()])\\1+", "$1");
測試
for (String str : new String[] { "(5)", "((5))", "((((5))))", "((((5))" }) {
str = str.replaceAll("([()])\\1+", "$1");
System.out.println(str);
}
輸出
(5)
(5)
(5)
(5)
解釋
( Start capture group
[()] Match a '(' or a ')'. In a character class, '(' and ')'
has no special meaning, so they don't need to be escaped
) End capture group, i.e. capture the matched '(' or ')'
\1+ Match 1 or more of the text from capture group #1. As a
Java string literal, the `\` was escaped (doubled)
$1 Replace with the text from capture group #1
另請參閱regex101.com以獲取演示。

TA貢獻1825條經驗 獲得超4個贊
我不確定括號是固定的還是動態的,但假設它們可能是動態的,你可以在這里做的是使用replaceAll然后使用String.Format來格式化字符串。
希望能幫助到你
public class HelloWorld{
public static void main(String []args){
String str = "((((5))))";
String abc = str.replaceAll("\\(", "").replaceAll("\\)","");
abc = String.format("(%s)", abc);
System.out.println(abc);
}
}
輸出:(5)
((5))我用and嘗試了上面的代碼(((5))),它產生了相同的輸出。
添加回答
舉報