Java 删除 Freemarker FTL 标签的正则表达式

Java regexp to remove Freemarker FTL tags

我正在尝试创建一个正则表达式来忽略字符串中的 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","");

但我找不到合适的正则表达式来使用。

替换后我要得到的最终String结果是"Hi, Mr Mrs ${name} I've a special offer for you."

以下模式应该符合您的预期:

\[/?#(.+?)\]

测试用例:

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.

应该这样做:

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"));
}