Best Alternative to Message Format

I have a line in the 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 that the message format cannot parse the string due to the first curly brace. I know that if I use '{', it will elude him, but the problem is that I have these types of strings, and I cannot manually add single quotes before and after the curly brace. Even if I write a function to do this, it will also slip away from curly braces for placeholder {0}.

Is this a better alternative to a message format like Ruby string interpolation. I just want to write a line pattern where I can replace some parts with a new line

+4
source share
3 answers

Newer versions of Java have java.util.Formatter with its printf methods. (There are also some API distribution options, such as String.format and PrintStream.printf).

There you will write

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

Replace all direct uses of MessageFormat your method. In your method, find curly braces and replace them based on context before passing it to MessageFormat . Something as stupid as

 s.replace("{", "'{'").replace("}", "'}'").replaceAll("'\\{'(\\d+)'\\}'", "{$1}") 

could do, depending on what arguments you use.

Do not use this (especially String.replaceAll ) if you are interested in efficiency. My solution is useful if you need to save the power of MessageFormat . An effective solution will analyze the input string once and recognize which curly braces should be specified. See the source code for Pattern.replaceAll how to do this.

+1
source

MessageFormat is simply dangerous to use if you don’t know exactly which line you feed it. Any presence of the { or } sign will crash everything you do. Here is a small method that I wrote just because I need it immediately. How effective I am, I have not tested. Typically, connecting to a database is 90% of the time spent responding to a request, so if something is effectively functional, it is usually worth doing. In jvm-only application you have to 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; } 
0
source

All Articles