我需要采用正则表达式模式并以编程方式逃避花括号.输入正则表达式将匹配以下模式(标签之前,之后和之间的文本):
&{token1}
&{token1}&{token2}&{tokenN...}
&{token1&{token2&{tokenN...}}}
到目前为止,我对除嵌套标签之外的所有内容都很好.这就是我所拥有的.
regex = regex.replaceAll("(&)(\\{)([^{}]+)(\\})", "$1\\\\$2$3\\\\$4");
我也试过使用迭代和递归,但我遇到的问题是,一旦最内层的令牌被转义,它就会与匹配混乱.
我尝试过负面的看守,但这并不符合我的预期.它只会匹配/替换最里面的令牌.
regex = regex.replaceAll("(&)(\\{)([^(?<!\\\\{)|(?<!\\\\})]+)(\\})", "$1\\\\$2$3\\\\$4");
有什么建议?提前致谢.
编辑:输入/输出示例
&{token1} //input
&\{token1\} //output
&{token1}&{token2}&{tokenN...} //input
&\{token1\}&\{token2\}&\{tokenN...\} //output
&{token1&{token2&{tokenN...}}} //input
&{token1&{token2&\{tokenN...\}}} //output
&\{token1&\{token2&\{tokenN...\}\}\} //expected output
//To throw a wrench into it, normal quantifiers should not be escaped
text{1,2}&{token1&{token2&{tokenN...}}} //input
text{1,2}&{token1&{token2&\{tokenN...\}}} //output
text{1,2}&\{token1&\{token2&\{tokenN...\}\}\} //expected output
编辑2:在此过程之外发生的事例的示例:标签将被解析为文本,然后最终,它应该是有效的正则表达式.
a{2}&{token1&{token2&{tokenN...}}} //input
a{2}&\{token1&\{token2&\{tokenN...\}\}\} //expected output of this regex
a{2}foobarbaz //expected output after tokens are resolved (&{token1} = foo, &{token2} = bar, &{tokenN...} = baz)
最佳答案 试试:
regex = regex.replaceAll("(?<=&)(?=\\{)|(?<!\\{\\d{0,6},?(\\d{0,6})?)(?=\\})","\\\\");
其中(0,6)确定可以有多少位数,6我认为足够了
Java示例:
public class Main {
public static void main(String[] args){
int i = 0;
String regex = "&{token1}&{token2}&{tokenN}\n" +
"&{token1&{token2&{tokenN}}}\n" +
"text{1,2}&{token1{1}&{token2{1,}&{tokenN{0,2}}}}\n";
regex = regex.replaceAll("(?<=&)(?=\\{)|(?<!\\{\\d{0,6},?(\\d{0,6})?)(?=\\})","\\\\");
System.out.println(regex);
}
}
输出:
&\{token1\}&\{token2\}&\{tokenN\}
&\{token1&\{token2&\{tokenN\}\}\}
text{1,2}&\{token1{1}&\{token2{1,}&\{tokenN{0,2}\}\}\}