AbVog
AbVog

Reputation: 1575

How to use single quotes with MessageFormat

On my current project, we are using properties files for strings. Those strings are then "formatted" using MessageFormat. Unfortunately, MessagFormat has a handling of single quotes that becomes a bit of a hindrance in languages, such as French, which use a lot of apostrophes.

For instance, suppose we have this entry

login.userUnknown=User {0} does not exist

When this gets translated into French, we get:

login.userUnknown=L'utilisateur {0} n'existe pas

This, MessageFormat does not like...

And I, do not like the following, i.e. having to use double quotes:

login.userUnknown=L''utilisateur {0} n''existe pas

The reason I don't like it is that it causes spellchecking errors everywhere.

Question: I am looking for an alternative to the instruction below, an alternative that does not need doubling quotes but still uses positional placeholders ({0}, {1}…). Is there anything else that can I use?

MessageFormat.format(Messages.getString("login.userUnkown"), username);

Upvotes: 17

Views: 8183

Answers (3)

Guildenstern
Guildenstern

Reputation: 3791

(U+2019 RIGHT SINGLE QUOTATION MARK) is the proper “apostrophe” to use in languages like English and French—not '.

isn’t a metacharacter in this format, which means that there is no need to escape anything.

Upvotes: 3

Frettman
Frettman

Reputation: 2271

Probably too late for you, but someone else might find this useful: Instead of Java's MessageFormat, use ICU (International Components for Unicode) (or rather its Java port ICU4J). It's basically a set of tools and data to support you in internationalizing your application. And among those tools is their own version of MessageFormat. It's very similar (maybe even backwards compatible) and can handle single quotes exactly like you want it. It can even handle doubled/escaped single quotes so you can try it as a drop-in replacement for Java's MessageFormat without having to unescape your single quotes first.

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

No there is no other way as it is how we are supposed to do it according to the javadoc.

A single quote itself must be represented by doubled single quotes '' throughout a String

As workaround, what you could do is doing it programmatically using replace("'", "''") or for this particular use case you could use the apostrophe character instead which is it would be even more correct actually than using a single quote.

Upvotes: 17

Related Questions