Domanda

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...?

È stato utile?

Soluzione 4

Since I haven't found another API which would provide the escaped Singlequote (' -> '') I will stay with my regular expression.

Altri suggerimenti

It helped me to do something like this:

`doesn''t`

The recommendation from ICU is to use the ASCII apostrophe (' U+0027) only for escaping syntax characters, and use the pretty single quote (’ U+2019) for actual apostrophes and single quotes in a message pattern.

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

Use the escapeEcmaScript method from Apache Commons Lang package.

See Stack Overflow questions:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top