替换字符串中的变量占位符 [英] Replacing variable placeholders in a string

查看:71
本文介绍了替换字符串中的变量占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似这样的字符串:您可以在 [开始日期 + 30] 之前使用促销活动".我需要用实际日期替换 [Start Date + 30] 占位符 - 这是销售的开始日期加上 30 天(或任何其他数字).[Start Date] 也可以单独出现,无需添加数字.此外,占位符内的任何额外空格都应被忽略,并且不会导致替换失败.

I have strings which look something like this: "You may use the promotion until [ Start Date + 30]". I need to replace the [ Start Date + 30] placeholder with an actual date - which is the start date of the sale plus 30 days (or any other number). [Start Date] may also appear on its own without an added number. Also any extra whitespaces inside the placeholder should be ignored and not fail the replacement.

在 Java 中最好的方法是什么?我正在考虑用于查找占位符的正则表达式,但不确定如何进行解析部分.如果只是 [开始日期] 我会使用 String.replaceAll() 方法,但我不能使用它,因为我需要解析表达式并添加天数.

What would be the best way to do that in Java? I'm thinking regular expressions for finding the placeholder but not sure how to do the parsing part. If it was just [Start Date] I'd use the String.replaceAll() method but I can't use it since I need to parse the expression and add the number of days.

推荐答案

你应该使用 StringBufferMatcher.appendReplacementMatcher.appendTail

You should use a StringBuffer and Matcher.appendReplacement and Matcher.appendTail

这是一个完整的例子:

String msg = "Hello [Start Date + 30] world [ Start Date ].";
StringBuffer sb = new StringBuffer();

Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(msg);

while (m.find()) {

    // What to replace
    String toReplace = m.group(1);

    // New value to insert
    int toInsert = 1000;

    // Parse toReplace (you probably want to do something better :)
    String[] parts = toReplace.split("\\+");
    if (parts.length > 1)
        toInsert += Integer.parseInt(parts[1].trim());

    // Append replaced match.
    m.appendReplacement(sb, "" + toInsert);
}
m.appendTail(sb);

System.out.println(sb);

输出:

Hello 1030 world 1000.

这篇关于替换字符串中的变量占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆