better alternative to message format
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
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);
Replace all direct uses of MessageFormat
by your method. In your method, look for the curly braces and replace them based on the context before passing it to MessageFormat
. Something as stupid as
s.replace("{", "'{'").replace("}", "'}'").replaceAll("'\\{'(\\d+)'\\}'", "{$1}")
could do, depending on what kinds of arguments you're using.
Don't use this (especially String.replaceAll
) in case you're concerned with efficiency. My solution is useful in case you need to preserve the power of MessageFormat
. An efficient solution would parse the input string once and recognize which braces should be quoted. Look at the source code of Pattern.replaceAll
for how it can be done.
MessageFormat is just dangerous to use if you don't know exactly what string you are feeding it with. Any presense of a {
or }
sign would crash whatever you are doing. Here is a small method I wrote just because I needed it immediately. How efficient it is I have not checked. Usually connecting to the DB is 90% of all time spent in answering a request, so if something is efficient functionally, it is usually worth doing. In a jvm-only application, you should be more careful...
public formatMessage(String pattern, String... replacements ) {
for(int i = 0; i < replacements.length; i++) {
pattern = pattern.replace("{" + i + "}", replacements[i]);
}
return pattern;
}
精彩评论