正则表达式删除方括号之间的字符和数字之外的所有内容

时间:2022-05-01 21:45:12

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&)

1 个解决方案

#1


2  

Translating my comments into an answer

将我的评论翻译成答案

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

您可以在Java中使用这种简单的解析来替换:

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&)

#1


2  

Translating my comments into an answer

将我的评论翻译成答案

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

您可以在Java中使用这种简单的解析来替换:

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&)