Replacing variable placeholders in a string

僤鯓⒐⒋嵵緔 提交于 2019-12-01 09:11:05

问题


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.

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.


回答1:


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

Here's a complete example:

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

Output:

Hello 1030 world 1000.


来源:https://stackoverflow.com/questions/10412339/replacing-variable-placeholders-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!