Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

I have a template string for which I need to add variables in it. Below is the string:

"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]".

Can anyone help me how I can able to replace the tokens to variables?

1 Answer

0 votes
by (26.7k points)

You can try the below code, which will help you to replace:

public static String replaceTokens(String text, 

                                   Map<String, String> 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();

}

I hope this will help.

Want to become a Java expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Tutorial for Beginners | Java Programming:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 20, 2019 in Java by Nigam (4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...