为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

浮云间 2023-03-17 10:33:42
我得到了一个字符串,我想用一个替换所有连续出现的左括号((5)) → (5)((((5))))→(5)我试过str = str.replaceAll("((", "(");然后我尝试了正则表达式错误str = str.replaceAll("\\((", "(");然后我试过了str = str.replaceAll("\\\\((", "(");我不断收到同样的错误!
查看完整描述

4 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

你试过这个吗?

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

'\' 是转义字符,因此每个特殊字符都必须以它开头。没有它们,正则表达式将其读取为用于分组的左括号,并期望有一个右括号。

编辑:最初,我以为他是想恰好匹配 2


查看完整回答
反对 回复 2023-03-17
?
交互式爱情

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以获取演示。


查看完整回答
反对 回复 2023-03-17
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您需要转义每个括号并添加+以说明连续出现的情况:

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


查看完整回答
反对 回复 2023-03-17
?
凤凰求蛊

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))),它产生了相同的输出。


查看完整回答
反对 回复 2023-03-17
  • 4 回答
  • 0 关注
  • 142 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信