Thursday, October 1, 2015

Replacing letters

The result:

The code:
import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Finder1 { public static void main(String[] args) { String exampleString = "" + "haaa is \"${haaa}\"\n"+ "fooo is \"${fooo}\"\n"; Map<String, String> varmap = new HashMap<String, String>(); varmap.put("haaa", "HAAA"); varmap.put("fooo", "FOOO"); Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}"); // Replace once { Matcher m = pattern.matcher(exampleString); StringBuffer sb = new StringBuffer(exampleString.length()); if(m.find()){ m.appendReplacement(sb, varmap.get(m.group(1))); } m.appendTail(sb); System.out.println("---replaceOnce---"); System.out.println(sb.toString()); } // Replace all { Matcher m = pattern.matcher(exampleString); StringBuffer sb = new StringBuffer(exampleString.length()); while(m.find()){ m.appendReplacement(sb, varmap.get(m.group(1))); } m.appendTail(sb); System.out.println("---replaceAll---"); System.out.println(sb.toString()); } } }