Removing single quotes for Java MessageFormat

There are already a few questions about MessagingFormat in general, but I have not found anything yet that answers my question. I know that single quotes break the pattern. If you use MessageFormat or Log4j, then something like โ€œdoesn'tโ€ can break possible placeholders.

See Inside String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, the pattern string "'{0}'" represents the string "{0}" rather than FormatElement. The single quotation mark itself must be represented by double single quotation marks โ€œalong the entire stringโ€.

A 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 a regular expression trying to replace only "single singlequotes" using the lookahead / lookbehind regular expression.

The regular expression replaces the examples:

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

I'm just wondering if there is any apache-commons utility (or any other library) that will handle "escapeSingleQuotes" for me instead of providing my own regular expression ...?

+6
source share
5 answers

Since I did not find another API that would provide a shielded Singlequote ('->' '), I will stay with my regex.

+3
source

This helped me do something like this:

 `doesn''t` 
+8
source

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

+3
source

For anyone with Android problems in string.xml , use \ '\' instead of a single quote.

+2
source

Use the escapeEcmaScript method from the Apache Commons Lang package.

See stack overflow questions:

0
source

Source: https://habr.com/ru/post/949005/


All Articles