better alternative to message format

Prim picture Prim · Aug 13, 2011 · Viewed 7.3k times · Source

I have a string of following format

Select * where {{0} rdfs:label "Aruba" } limit 10

Now I would like to replace {0} with some new text, but the problem is message format is unable to parse the string due to the first curly bracket. I know if i use '{' it would escape it, but the problem is I have loads of such type of string and I cannot manually add single quotes before and after the curly bracket. Even if I write a function to do this, it would escape the curly brackets for the placeholder {0} as well.

Is their a better alternative to message format, something like ruby string interpolation. I just want a way to write a string template where i can replace certain parts with new string

Answer

Paŭlo Ebermann picture Paŭlo Ebermann · Aug 13, 2011

Newer Java versions have java.util.Formatter with its printf like methods. (There are also some variants of them dispersed throughout the API, like String.format and PrintStream.printf).

There you would write

String some_text = "Hello";
String pattern = "Select * where {%s rdfs:label \"Aruba\" } limit 10";
String replaced = String.format(pattern, some_text);