如何找到所有“((”)并将其替换为“(”?

时间:2019-07-09 18:15:32

标签: java

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

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

我尝试过

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

并得到正则表达式模式错误 然后我尝试了

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

然后我尝试了

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

我一直遇到同样的错误!

4 个答案:

答案 0 :(得分:4)

您尝试过吗?

str = str.replaceAll("\\({2,}", "(");

'\'是转义字符,因此每个特殊字符都必须以它开头。没有它们,regex会将其读取为用于分组的开括号,并期望闭括号。

编辑:最初,我以为他试图精确匹配2

答案 1 :(得分:1)

您需要转义每个括号并添加+来解决连续出现的情况:

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

答案 2 :(得分:1)

假设括号不需要成对,例如((((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进行演示。

答案 3 :(得分:0)

我不确定方括号是固定的还是动态的,但是假设它们是动态的,则可以使用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))(((5)))尝试了上面的代码,并且产生了相同的输出。