正则表达式:如何删除由某些字符限定的子字符串?

时间:2017-08-04 08:22:02

标签: java regex

我不确定适当的正则表达式是什么:

String s = "[Don't remove] Don't remove [Remove | Don't remove]";

我想删除[和|之间的所有内容但不是[和]。所以输出是:

"[Don't remove] Don't remove Don't remove]"

我试过这样做,

s = s.replaceAll("\\[.*?\\|", "");

但我最终得到了这样的东西。

"Don't remove]"

现在我迷路了。我仍然是正则表达式的新手,非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

使用不允许在[^\[|]*[之间匹配任何其他|[的带有字符的字符|

String s = "[Don't remove] Don't remove [Remove | Don't remove]";
s = s.replaceAll("\\[[^\\[|]*\\|", "");
System.out.println(s); // => [Don't remove] Don't remove  Don't remove]

查看regex demoonline Java demo

<强>详情