【问题标题】:Remove only nested curly brackets from String using java使用java仅从String中删除嵌套的大括号
【发布时间】:2014-05-21 15:22:59
【问题描述】:

我有这个任务,其中消息中有嵌套的大括号。我的动机是只删除最里面的大括号,消息的其余部分保持不变。字符串消息的示例如下:

enter code here Input :  {4:{CLIENT ACCOUNT} :-}
                Output:  {4: CLIENT ACCOUNT :-}

所以基本上我们需要确保删除最里面的大括号,其余内容保持不变。如何去做?

我能够使用以下伪代码删除一级大括号:

enter code here
String str ="{CLIENT ACCOUNT}";
String regex = "(\\{|\\})"; 
str = str.replaceAll(regex, "");
System.out.println("Formatted String is--"+str);

但我不知道如何使用正则表达式来忽略第一级大括号。任何帮助将不胜感激。

【问题讨论】:

    标签: java regex parsing


    【解决方案1】:

    我不知道如何使用 java 正则表达式来做到这一点,但你可以这样做:

    String str = "someContent";
    String newStr = "";
    int level = 0;
    for (int i = 0; i < str.length(); ++i){
        if (str.charAt(i) == '{'){
            if (level == 0) //check before incrementing
                newStr += "{";
            level++;
        } else if (str.charAt(i) == '}'){
            level--;
            if (level == 0) //check after incrementing
                newStr += "}";
        } else {
            newStr += str.charAt(i);
        }
    }
    
    return newStr;
    

    您基本上会逐步遍历字符串中的每个字符,并记住您已经看到了多少个 '{'s 和 '}'s。然后,只有在净计数为零(或最外面的括号)时才将它们打印出来

    【讨论】:

    • 嗨,哈里森,您的 java 代码在集成到程序中后似乎运行良好。非常感谢。过去几天我一直在使用正则表达式,但无济于事。我会接受你的回答为已接受的答案。干杯
    【解决方案2】:

    不是最漂亮的答案..它不适用于深度嵌套的大括号,但它适用于多组嵌套的大括号。

    (\{[^}]+?|\G[^{]*)\{([^}]+)\}
    $1 $2
    

    Demo

    {1:{CLIENT ACCOUNT}, 2:{FOO {OOPS} BAR}, 3:{TEST}}
    {1: CLIENT ACCOUNT, 2: FOO {OOPS BAR}, 3: TEST}
    

    在上面的演示中,您可以看到当我们有一组多嵌套的大括号时导致的错误。这是因为我们假设内容将是[^}]+,或者不是右括号。这是一个扩展的解释:

    (        (?# start capture)
      \{     (?# match { literally)
      [^}]+? (?# lazily match 1+ non-})
     |       (?# OR)
      \G     (?# start back from last match, still in a curly bracket)
      [^{]*  (?# match 0+ non-{ characters)
    )        (?# end capture)
    \{       (?# match { literally)
    (        (?# start capture)
      [^}]+  (?# match 1+ non-} characters)
    )        (?# end capture)
    \}       (?# match } literally)
    

    【讨论】:

    • 感谢 sam 的详细解释。只有两个级别的嵌套。仅此而已。在这种情况下如何处理。我尝试使用您的答案,但它没有按预期运行。跨度>
    • “两层嵌套”是指在我的示例{1:{CLIENT ACCOUNT}, 2:{FOO {OOPS} BAR}, 3:{TEST}} 中的{FOO {OOPS} BAR} 吗?如果是这样,您期望的结果是什么......请更新 OP :)
    • Sam,通过两层嵌套,我的意思是:如果输入为:{4:{CLIENT ACCOUNT}:-},则输出为:{4:CLIENT ACCOUNT:-}。请检查我更新的问题。它清楚地提到了。
    猜你喜欢
    • 2019-08-11
    • 2010-12-26
    • 2023-02-06
    • 2022-10-19
    • 2011-02-10
    • 2020-02-14
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多