Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to remove everything but characters and numbers between Square brackets

I used

value.replaceAll("[^\\w](?=[^\\[]*\\])", "");

it works fine if in the following case

[a+b+c1 &$&$/]+(1+b&+c&)

produces:

[abc1]+(1+b&+c&)

but in case of following string it only removes the square brackets within square brackets in the first run

[a+b+c1 &$&$/[]]+(1+b&+c&)

produces:

[a+b+c1 &$&$/]+(1+b&+c&)
like image 568
Xeshan J Avatar asked Jun 09 '15 06:06

Xeshan J


1 Answers

Translating my comments into an answer

You can use this simple parsing in Java for your replacement:

String s = "[a+b+c1 &$&$/[]]+(1+b&+c&)";
int d=0;
StringBuilder sb = new StringBuilder();
for (char ch: s.toCharArray()) {
    if (ch == ']')
        d--;
    if (d==0 || Character.isAlphabetic(ch) || Character.isDigit(ch))
        sb.append(ch);
    if (ch == '[')
        d++;
}
System.out.println(sb);
//=> [abc1]+(1+b&+c&)
like image 132
anubhava Avatar answered Oct 02 '22 03:10

anubhava