user2380243
user2380243

Reputation: 3

Remove only nested curly brackets from String using java

I have this task where in the message has nested curly brackets.My motive is to get to remove only the inner most curly brackets and the rest of the message stays the same.A sample of The string message is as follows :

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

So Basically we need to ensure to remove the innermost curly brackets,rest of the content staying the same.How to go about it ?

I was able to remove one level of braces using the following pseudo code :

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

but i am stuck as to what to use the regex for ignoring the first level of curly brackets.any help will be highly appreciated.

Upvotes: 0

Views: 1110

Answers (2)

Sam
Sam

Reputation: 20486

Not the prettiest of answers..it won't work with deeply nested curly brackets, but it will work with multiple sets of nested curly brackets.

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

Demo

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

In the above demo, you can see the error caused when we have a multi-nested set of curly brackets. This is because we assume the contents will be [^}]+, or anything but a closing bracket. Here is an expanded explanation:

(        (?# 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)

Upvotes: 0

Harrison
Harrison

Reputation: 688

I don't know how to do this using a java regex, but you could do something like this:

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;

You basically step through each character in the string and remember how many '{'s and '}'s you have already seen. Then you only print them out if you are at a net count of zero (or the outermost brackets)

Upvotes: 1

Related Questions