Note that there are some explanatory texts on larger screens.

plurals
  1. POJava string templatizer / formatter with named arguments
    primarykey
    data
    text
    <p>Is there a standard or at least widespread implementation of something like <code>String.format</code>, but with named arguments?</p> <p>I'd like to format a templatized string in a way like that:</p> <pre><code>Map&lt;String, Object&gt; args = new HashMap&lt;String, Object&gt;(); args.put("PATH", "/usr/bin"); args.put("file", "foo"); String s = someHypotheticalMethod("#{PATH}/ls #{file}"); // "/usr/bin/ls foo" </code></pre> <p>Technically, it's almost the same as:</p> <pre><code>String[] args = new String[] { "/usr/bin", "foo" }; String s = String.format("%1$s/ls %2$s", args); // "/usr/bin/ls foo" </code></pre> <p>but with named arguments.</p> <p>I'm aware of:</p> <ul> <li><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html">String.format</a></li> <li><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html">Formatter</a></li> <li><a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/text/MessageFormat.html">MessageFormat</a></li> </ul> <p>but all of them use ordered or at least numbered arguments, not named ones. I know it's trivial to implement one, but is there a mechanism I'm looking for in standard Java libraries or at least in Apache Commons / Guava / something similar, without bringing in high-profile template engines?</p> <p><strong>NOTE</strong>: I'm not really interested in full-blown template engines, with features like some imperative / functional logic, flow control, modifiers, sub-templates / inclusions, iterators, etc. Generally the following method is a working 4-line implementation - that's all I need:</p> <pre><code>public static String interpolate(String format, Map&lt;String, ? extends Object&gt; args) { String out = format; for (String arg : args.keySet()) { out = Pattern.compile(Pattern.quote("#{" + arg + "}")). matcher(out). replaceAll(args.get(arg).toString()); } return out; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload