Search code examples
javamessageformat

What is the equivalent of Pattern.quote() for MessageFormat?


I ran into an issue today with the following code using Spring:

String tabTitle = messageSource.getMessage(tabName, new Object[] {}, tabName, locale)

This is used to get the displayed titles of a series of tabs at the top of our site (an instance of uPortal). The problem is that if tabName contains a single quote, it gets automatically removed from the result. For example What's For Lunch becomes Whats For Lunch.

I've tracked down why and it is because the 3rd parameter in that method is supposed to be of the format specified in java.text.MessageFormat. 2 single quotes are needed.

Because we're not passing any parameters with the format, I can safely escape any special characters in the tabName before passing it in as the 3rd parameter. I could manually replace the single quotes here with 2 single quotes, but what I'd really like is something like Pattern.quote(), only for the MessageFormat language, that would be guaranteed to handle all escaping. Does anything like this exist?


Solution

  • There isn’t any method for it, but enclosing the entire text in ASCII single-quote characters will accomplish the same thing. You can do ''' substitution as you’ve described, then surround the text with '. From the MessageFormat documentation:

    For example, pattern string "'{''}'" is interpreted as a sequence of '{ (start of quoting and a left curly brace), '' (a single quote), and }' (a right curly brace and end of quoting), not '{' and '}' (quoted left and right curly braces): representing string "{'}", not "{}".