i having string template containing $variables needs replaced.
string template: "hi name $name.\ni $age old. $sex"
the solution tried verifying not work in java program. http://regexr.com/3dtq1
further, referred https://www.regex101.com/ not check if pattern works java. but, while going through 1 of tutorials found "$ matches end of line". what's best way replace tokens in template 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 name $name.\ni $age old. $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(matcher.group(1)); if (replacement != null) { // matcher.appendreplacement(buffer, replacement); // see comment matcher.appendreplacement(buffer, ""); buffer.append(replacement); } } matcher.appendtail(buffer); system.out.println(buffer.tostring()); } }
you using matcher.group(1) didn't define group in regexp (( )), can use group() whole matched string, want.
replace line:
string replacement = replacements.get(matcher.group(1)); with:
string replacement = replacements.get(matcher.group().substring(1)); notice substring, map contains words, matcher match $, need search in map "$age".substring(1)" replacement on whole $age.
Comments
Post a Comment