java - 哪些字符串替换 Java API(模板库)可用于进行条件和自定义字符串替换?

标签 java substitution

我正在寻找一个开源 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}].

<ACTION_DATETIME '" at "MM/dd/yyyy" on "HH:mm AM'>告诉我们要使用什么日期以及该日期的格式。

[ {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 上。

最佳答案

我认为 @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 包含用模型中的值填充的模板。

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

关于java - 哪些字符串替换 Java API(模板库)可用于进行条件和自定义字符串替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46717988/

相关文章:

java - 如何计算一个月内有多少个星期二?

Vim 可变长度通配符搜索和替换?

regex - 如何使用 Perl 通过正则表达式替换在连续匹配之间散布字符?

linux - perl -p -i -e 将行替换为包含符号的文本

excel - 绞尽脑汁试图替换公式中的子字符串而不替换稍大的子字符串?

java - Java中如何正确发送和接收多个XBee的数据包

java - Struts 2 显示西类牙语文本问题

java - SOAP - 没有命名空间的前缀

Java hibernate获取所有实体

regex - 我编写了一个正则表达式来将子字符串与其周围的空格匹配,但这效果不佳