【问题标题】:What String Replacement Java API's (Templating Library) are available to do conditional and custom string replacment?哪些字符串替换 Java API(模板库)可用于进行条件和自定义字符串替换?
【发布时间】:2017-10-12 20:04:12
【问题描述】:

我正在寻找一种开源 Java API,它允许我根据自定义标签进行可配置的字符串替换。

示例模板:

Your did something<ACTION_DATETIME '" at "HH:mm AM" on "MM/dd/yyyy'> in[ {CITY}, {STATE}][ {ZIP5}]. Your's truly, [ {FIRST_INITIAL}][ {LAST_NAME}].

&lt;ACTION_DATETIME '" at "MM/dd/yyyy" on "HH:mm AM'&gt; 告诉我们要使用的日期和日期的格式。

[ {CITY}, {STATE}] 告诉我们将城市和州放在此处,如果任一字段为空,则排除方括号之间的所有内容

示例结果:

Your did something at 1:32 PM on 10/13/2017 on in Mansfield, OH 44906. Your's truly, J Tully.

我已经使用正则表达式和正则字符串替换部分构建了一个解决方案,但是我希望有一个更强大的预构建解决方案。

我查看了 Commons Lang3 的 StrSubstitutor,虽然它处理简单和自定义的替换,但它似乎没有更多的语法驱动替换。

更新#1

目前停留在 Java 1.6。

【问题讨论】:

  • 听起来你现在正在寻找一个模板库。你试过百里香吗?
  • Java 9 有一个Matcher.replaceAll,您可以在其中提交函数
  • 是的,我正在寻找一个模板库。不幸的是,此时升级到 Java 9 不是一个选择。在客户批准我们升级之前,我们目前停留在 Java6 上。
  • 按照建议查看 Thymeleaf 和 Freemarker,看看它们是否符合我的要求。

标签: java substitution


【解决方案1】:

我认为@TinkerTenorSoftwareGuy 对模板库的建议是最好的选择。有很多,我用Freemarker一点。

基本上你有一个模板:

You did ${action} at ${date} in ${city} ${state} ${zip}. Yours truly, ${firstName} ${lastName}.

还有一个包含数据的模型(一个java类):

class MyTemplate extends StringTemplate {

    public MyTemplate(String action, Date date, /* etc */ ) { /* set the model state */ }

    public String getTemplateFileLocation() { /* point to the template file */ }

    public String process() { /* process the template and return the string */ }

    public String getAction() { /* return the action as a string */ }

    public String getDate() { /* return the formatted date as a string, i.e. */ 
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        return df.format(date);
    }

    public String getCity() { /* return the city as a string */ }

    public String getState() { /* return the state as a string */ }

    public String getZip() { /* return the zip code as a string */ }

    public String getFirstName() { /* return the first name as a string */ }

    public String getLastName() { /* return the last name as a string */ }
}

然后在您的代码中,您可以实例化模板并对其进行处理。处理模板会将模板中的${firstName} 实例替换为模型中getFirstName() 的返回值(依此类推,对于每个变量):

StringTemplate template = new MyTemplate(action, date, city, state, zip, firstName, lastName);
String letter = template.process();

现在letter 包含填充了模型值的模板。

有很多不同的模板库,但这是基本思想。

【讨论】:

  • 如果值为空,是否允许剥离文本子集?示例:对于[in {CITY}, {STATE}] 之类的内容,如果任一值为 null,我想阻止方括号(或等效项)之间的所有内容被删除。注意:“in”和“,”需要在每个模板的基础上在数据库中进行配置。
  • 当然,你可以在模型中做所有这些事情——它只是 Java,你可以随心所欲地转换文本,模板本身应该很简单。
猜你喜欢
  • 2015-11-09
  • 2014-09-10
  • 2021-10-08
  • 1970-01-01
  • 2023-04-01
  • 2021-01-27
  • 1970-01-01
  • 2013-07-09
相关资源
最近更新 更多