Alex
Alex

Reputation: 1131

Replacing variable placeholders in a string

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.

Upvotes: 2

Views: 7364

Answers (1)

aioobe
aioobe

Reputation: 421170

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.

Upvotes: 3

Related Questions