Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quotes for Java MessageFormat

There are already several questions about the MessagingFormat in general, but I haven't found anything yet that answers my question. I'm aware, that single quotes will break the pattern. If you use MessageFormat or Log4j something like "doesn't" can break possible placeholders.

See Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String.

Simple example:

@Test
public void test() {
    String pattern = "{0} doesn't show values ( {1}, {2}, {3}, {4} )";
    final Object[] args = { "Testpattern", 100, 200, 300, 400 };
    System.out.println(MessageFormat.format(pattern, args));
    pattern = pattern.replaceAll("(?<!')'(?!')", "''");
    System.out.println("Replaced singlequotes: " + MessageFormat.format(pattern, args));
}

Output:

Testpattern doesnt show values ( {1}, {2}, {3}, {4} )
Replaced singlequotes: Testpattern doesn't show values ( 100, 200, 300, 400 )

So, if I replace all single quotes using a regular expression, it will work. I just made up the regular expression trying to only replace "single singlequotes" using regular expression lookahead/lookbehind.

Regular expression replace examples:

    doesn't -> doesn''t
    doesn''t -> doesn''t
    doesn'''t -> doesn'''t

I just wonder, if any apache-commons utility (or any other library) exists, which will handle the "escapeSingleQuotes" for me instead of providing my own regular expression...?

like image 831
proko Avatar asked Jul 09 '13 09:07

proko


People also ask

How do you escape a single quote in Java?

Output: In this example, GeeksforGeeks has to be written within single quotes. Since, for defining string literal, we are using a single-quote string, that's why we need to escape the single-quote(' ') using a backslash(\) within the string.

How do you handle a single quote in a String in Java?

Core Java bootcamp program with Hands on practice Above, for single quote, we have to mention it normally like. However, for double quotes, use the following and add a slash in the beginning as well as at the end. String str2 = "\"This is it\"!"; The following is an example.

How do you escape braces in Java?

A character with a backslash (\) just before it is an escape sequence or escape character.


2 Answers

It helped me to do something like this:

`doesn''t`
like image 113
Mat Avatar answered Sep 22 '22 15:09

Mat


For everyone that has Android problems in the string.xml, use \'\' instead of single quote.

like image 42
Uriel Frankel Avatar answered Sep 22 '22 15:09

Uriel Frankel