fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class Main {
  7.  
  8. public static void main(String[] args) {
  9. Map<String, String> tokensMap = new HashMap<>();
  10. tokensMap.put("fizz", "FIZZZZZ");
  11. tokensMap.put("buzz", "BUZZZZ");
  12. System.out.println(substituteAllTokens(tokensMap, "hth trh${fizz} trh thtrht ${buzz} trhthh trh trh trh"));
  13. }
  14.  
  15. private static String substituteAllTokens(Map<String, String> tokensMap, String toInspect) {
  16. String regex = "\\$\\{([^}]*)\\}";
  17. Pattern pattern = Pattern.compile(regex);
  18. Matcher matcher = pattern.matcher(toInspect);
  19. while (matcher.find()) {
  20. String token = matcher.group(); // Ex: ${fizz}
  21. String tokenKey = matcher.group(1); // Ex: fizz
  22. String replacementValue = null;
  23.  
  24. if (tokensMap.containsKey(tokenKey))
  25. replacementValue = tokensMap.get(tokenKey);
  26. else
  27. throw new RuntimeException("String contained an unsupported token.");
  28.  
  29. toInspect=toInspect.replaceFirst(Pattern.quote(token), replacementValue);
  30. //matcher.reset(toInspect);//REMOVE THIS AND see if it works
  31.  
  32. }
  33.  
  34. return toInspect;
  35. }
  36. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
hth  trhFIZZZZZ trh thtrht  BUZZZZ trhthh trh trh trh