regex - How to implement "supplant" in java -
"supplant() variable substitution on string. scans through string looking expressions enclosed in { } braces. if expression found, use key on object, , if key has string value or number value, substituted bracket expression , repeats."
more specifically, trying somethink like:
public static string supplant(charsequence message, map<string,object> params) i trying use regex \{([\w]*)\} capture variables , lookup map , replace, couldn't write regex matches...
how implement supplant() in java?
what describe more commonly called templating. there many templating applications , libraries out there, if want quick-and-dirty solution, can implemented regexes.
in many regex flavors use built-in callback or callout mechanism, php's preg_replace_callback function, or perl's /e , /ee modifiers. java doesn't have that, provides api let implement yourself. here's example:
import java.util.*; import java.util.regex.*; public class test { public static void main(string[] args) throws exception { string s = "lorem ipsum {foo} impedit civibus ei pri, legimus\n" + "antiopam no {marco}, quo id everti forensibus maiestatis."; map<string,object> p = new hashmap<string,object>() {{ put("foo", "bar"); put("marco", "polo!"); }}; system.out.printf("%s%n%n%s%n", s, supplant(s, p)); } public static charsequence supplant(charsequence message, map<string,object> params) { matcher m = pattern.compile("\\{(\\w+)\\}").matcher(message); stringbuffer sb = new stringbuffer(); while (m.find()) { m.appendreplacement(sb, ""); string key = m.group(1); sb.append(params.get(key).tostring()); } m.appendtail(sb); return sb.tostring(); } } obviously code leaves out essential components (principally exception handling), demonstrates main points of technique:
- capture content within braces using parentheses, access calling
group(1)on matcher. - use
appendreplacement(sb, "")append whatever text appeared between previous match (if there one) , current one. - look replacement , append using stringbuffer's
append()method. (you could combine steps 2 , 3 passing replacement string second argumentappendreplacement(), have watch out dollar signs , backslashes in string, receive special treatment. way simpler.) - use
appendtail(sb)append whatever's left after last match.
several people have published helper classes let accomplish sort of task without having write boilerplate code. favorite elliott hughes's rewriter.
Comments
Post a Comment