如何找到所有“((”并将它们替换为“(”?

我得到了一个字符串,我想用一个替换所有连续出现的左括号

  • ((5)) → (5)

  • ((((5))))(5)

我试过

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

然后我尝试了正则表达式错误

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

然后我试过了

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

我不断收到同样的错误!


浮云间
浏览 143回答 4
4回答

回首忆惘然

你试过这个吗?str = str.replaceAll("\\({2,}", "(");'\' 是转义字符,因此每个特殊字符都必须以它开头。没有它们,正则表达式将其读取为用于分组的左括号,并期望有一个右括号。编辑:最初,我以为他是想恰好匹配 2

交互式爱情

假设括号不需要配对,例如((((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以获取演示。

守着星空守着你

您需要转义每个括号并添加+以说明连续出现的情况:str = str.replaceAll("\\(\\(+","(");

凤凰求蛊

我不确定括号是固定的还是动态的,但假设它们可能是动态的,你可以在这里做的是使用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))),它产生了相同的输出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java