dataEnthusiast dataEnthusiast - 2 months ago 7x
Java Question

How to replace tokens in java using regex?

I am having a string template containing $variables which needs to be replaced.

String Template: "hi my name is $name.\nI am $age old. I am $sex"

The solution which i tried verifying does not work in the java program.

Further, I referred to where i could not check if the pattern works for java. But, while going through one of the tutorials I found that "$ Matches end of line". what's the best way to replace the tokens in the template with the variables?

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternCompiler {
static String text = "hi my name is $name.\nI am $age old. I am $sex";
static Map<String,String> replacements = new HashMap<String,String>();
static Pattern pattern = Pattern.compile("\\$\\w+");
static Matcher matcher = pattern.matcher(text);

public static void main(String[] args) {

replacements.put("name", "kumar");
replacements.put("age", "26");
replacements.put("sex", "male");

StringBuffer buffer = new StringBuffer();

while (matcher.find()) {
String replacement = replacements.get(;
if (replacement != null) {
// matcher.appendReplacement(buffer, replacement);
// see comment
matcher.appendReplacement(buffer, "");




You are using but you didn't define any group in the regexp (( )), so you can use only group() for the whole matched string, which is what you want.

Replace line:

String replacement = replacements.get(;


String replacement = replacements.get(;

Notice the substring, your map contains only words, but matcher will match also $, so you need to search in map for "$age".substring(1)" but do replacement on the whole $age.