我正在尝试创建一个regexp来忽略String中的Freemarker FTL标记。
我有一个包含文字的模板和FTL tags,例如"Hi, [#if gender="Male"]Mr[#elseif]Mrs[/#if] ${name} I've a special offer for you."
我想只替换FTL标签,所以只有[#something]
模式的标签:我使用方括号语法。
理想情况下,我应该致电“myString".replaceAll("regex","");
但是我无法找到合适的正则表达式。
我想在替换后获得的最终字符串结果为"Hi, Mr Mrs ${name} I've a special offer for you."
答案 0 :(得分:2)
以下模式应该符合您的期望:
\[/?#(.+?)\]
测试用例:
public class Test {
private static final String PATTERN = "\\[/?#(.+?)\\]";
private static final String TEXT = "Hi, [#if gender=\"Male\"]Mr[#elseif]Mrs[/#if] ${name} I've a special offer for you.";
public static void main(String[] args) {
String out = TEXT.replaceAll(PATTERN, "");
System.out.println(out);
}
}
输出:
Hi, MrMrs ${name} I've a special offer for you.
答案 1 :(得分:1)
这应该这样做:
public static void main(String[] args) {
String template = "<html>[BR]\n"
+ "<head>[BR]\n"
+ " <title>Welcome!</title>[BR]\n"
+ "</head>[BR]\n"
+ "<body>[BR]\n"
+ " [#-- Greet the user with his/her name --][BR]\n"
+ " <h1>Welcome ${user}!</h1>[BR]\n"
+ " <p>We have these animals:[BR]\n"
+ " <ul>[BR]\n"
+ " [#list animals as animal][BR]\n"
+ " <li>${animal.name} for ${animal.price} Euros[BR]\n"
+ " [/#list][BR]\n"
+ " </ul>[BR]\n"
+ "</body>[BR]\n"
+ "</html>";
System.out.println("************ORIGINAL TEMPLATE**************");
System.out.println(template);
System.out.println("************REPLACED TEMPLATE**************");
System.out.println(template.replaceAll("\\[/?#(.*?)\\]", "\u001B[33mREPLACEMENT\u001B[0m"));
}