Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Last active August 29, 2015 14:21
Show Gist options
  • Save egonelbre/f306dbd2445dd704edd3 to your computer and use it in GitHub Desktop.
Save egonelbre/f306dbd2445dd704edd3 to your computer and use it in GitHub Desktop.
public static String replace(String pattern, String input, Function<String, String> translate){
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
StringBuffer result = new StringBuffer();
while(m.find()){
String r = translate.apply(m.group());
m.appendReplacement(result, Matcher.quoteReplacement(r));
}
m.appendTail(result);
return result.toString();
}
public static String replaceSymbols(String input, Function<String, String> translate){
Map<String, String> cache = new HashMap<String, String>();
return replace("\\$[a-zA-Z]\\w*", input, s -> {
if(!cache.containsKey(s)){ cache.put(s, translate.apply(s)); }
return cache.get(s);
});
}
function ReplaceSymbols(input, translate) {
var cache = {};
return input.replace(/$[a-zA-Z]\w*/g, function(symbol){
if(cache[symbol] == null) { cache[symbol] = translate(symbol); }
return cache[symbol];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment