我不确定适当的正则表达式是什么:
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]"
现在我迷路了。我仍然是正则表达式的新手,非常感谢任何帮助。谢谢!
答案 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 demo和online Java demo。
<强>详情
\\[
- 文字[
[^\\[|]*
- negated character class匹配除[
和|
以外的任何0 +字符\\|
- 文字|
符号。