在java中,我有一个像这样的字符串:
"bla bla bla bla [BACK] bla bla bla [bla bla [GO] bla bla bla bla [bla"
我想找到一个规则用正则表达式替换开始标记“[”和“(开始)”和结束标记“]”用“(结束)”.
应忽略“单独的起始标签或结束标签”.
结果是我得到以下内容:
bla bla bla bla (start)BACK(end) bla bla bla [ bla bla (start)GO(end) bla bla bla bla [bla
解决方法:
String resultString = subjectString.replaceAll(
"(?x) # Turn on verbose mode \n" +
"\\[ # Match a [ \n" +
"( # Match and capture in group 1: \n" +
"[^\\[\\]]* # Any number of characters except brackets\n" +
") # End of capturing group \n" +
"\\] # Match a ]", "(start)$1(end)");
将仅匹配/替换平衡的[/]对,它们之间没有括号.