java string 替换一批_如何替换Java String中的一组标记?

问题

我有以下模板字符串:"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"。

我还有名称,发票号和截止日期的字符串变量 - 用变量替换模板中的标记的最佳方法是什么?

(请注意,如果变量恰好包含令牌,则不应替换它)。

编辑

感谢@laginimaineb和@ alan-moore,这里是我的解决方案:

public static String replaceTokens(String text,

Map replacements) {

Pattern pattern = Pattern.compile("\\[(.+?)\\]");

Matcher matcher = pattern.matcher(text);

StringBuffer buffer = new StringBuffer();

while (matcher.find()) {

String replacement = replacements.get(matcher.group(1));

if (replacement != null) {

// matcher.appendReplacement(buffer, replacement);

// see comment

matcher.appendReplacement(buffer, "");

buffer.append(replacement);

}

}

matcher.appendTail(buffer);

return buffer.toString();

}

#1 热门回答(91 赞)

我真的认为你不需要使用模板引擎或类似的东西。你可以使用68882268方法,如下所示:

String template = "Hello %s Please find attached %s which is due on %s";

String message = String.format(template, name, invoiceNumber, dueDate);

#2 热门回答(62 赞)

最有效的方法是使用匹配器不断查找表达式并替换它们,然后将文本附加到字符串构建器:

Pattern pattern = Pattern.compile("\\[(.+?)\\]");

Matcher matcher = pattern.matcher(text);

HashMap replacements = new HashMap();

//populate the replacements map ...

StringBuilder builder = new StringBuilder();

int i = 0;

while (matcher.find()) {

String replacement = replacements.get(matcher.group(1));

builder.append(text.substring(i, matcher.start()));

if (replacement == null)

builder.append(matcher.group(0));

else

builder.append(replacement);

i = matcher.end();

}

builder.append(text.substring(i, text.length()));

return builder.toString();

#3 热门回答(39 赞)

你可以尝试使用像Apache Velocity这样的模板库。

http://velocity.apache.org/

这是一个例子:

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.Velocity;

import java.io.StringWriter;

public class TemplateExample {

public static void main(String args[]) throws Exception {

Velocity.init();

VelocityContext context = new VelocityContext();

context.put("name", "Mark");

context.put("invoiceNumber", "42123");

context.put("dueDate", "June 6, 2009");

String template = "Hello $name. Please find attached invoice" +

" $invoiceNumber which is due on $dueDate.";

StringWriter writer = new StringWriter();

Velocity.evaluate(context, writer, "TemplateName", template);

System.out.println(writer);

}

}

输出将是:

Hello Mark. Please find attached invoice 42123 which is due on June 6, 2009.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值