Regular expression to remove everything except 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&) 

gives:

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

but in the case of the next line, it removes the square brackets in square brackets in the first run

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

gives:

 [a+b+c1 &$&$/]+(1+b&+c&) 
+6
source share
1 answer

Translation of my comments in response

You can use this simple parsing in Java to replace:

 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&) 
+2
source

Source: https://habr.com/ru/post/988762/


All Articles