我正在尝试创建一个正则表达式来删除字符串中的Freemarker插值标记。我的文本和插值模板为"Hi customer, we remember your appointment ${date?string["dd"]}"
我想删除/重新插入这个有点特殊的插值标记,因为它有问号内部。 我试图以这种方式创建正则表达式:
String myString = "Hi customer, we remember your appointment ${date?string["dd"]}"
myString = myString.replaceAll(Pattern.quote("${date?string[\"dd\"]}"), "xx");
但不起作用。我在哪里弄错了?
答案 0 :(得分:1)
不要忘记将replaceAll
方法的返回值分配给原始字符串,因为replaceAll
(或任何其他String
API)不会更改基础不可变String对象:
String myString = "Hi customer, we remember your appointment ${date?string[\"dd\"]}";
myString = myString.replaceAll(Pattern.quote("${date?string[\"dd\"]}"), "xx");
//=> Hi customer, we remember your appointment xx
答案 1 :(得分:0)
使用正则表达式,你可以这样做:
get_item
结果字符串是:
String myString = "Hi customer, we remember your appointment ${date?string[\"dd\"]}";
myString = myString.replaceAll("\\$\\{date\\?string\\[\"dd\"\\]\\}", "xx");
答案 2 :(得分:0)
我将字符串分成4个逻辑组,然后将所需内容组合在一起。
尝试以下正则表达式:
(.*?)(?:\$\{.*?\"([^\"]+).{3})(.*)
示例:
String text = "Hi customer, we remember your appointment ${date?string[\"dd\"]}";
String replacement_text = "xxx";
String rx = "(.*?)(?:\\$\\{.*?\"([^\"]+).{3})(.*)";
Pattern regex = Pattern.compile(rx, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher regexMatcher = regex.matcher(text);
String result = regexMatcher.replaceAll("$1" + replacement_text + "$3");
System.out.println(result);
代码将发出:
Hi customer, we remember your appointment xxx
但是,如果您要提取标记的内容,即dd
,只需将replacement_text
的值替换为$2
,您就会得到
Hi customer, we remember your appointment dd