Wednesday, November 29, 2006

Resource bundle syntax gotchas

What's wrong with this property resource bundle entry?

importantMessage={0}'s account status is now {1}

For people who are experienced with resource bundles, this is probably obvious: that single ' escapes the rest of the string from MessageFormat processing. Also, since it's an escape character, it will not be displayed, regardless of MessageFormat. It's too bad MessageFormat doesn't fail when the ' goes unclosed. A double ' acts as a replacement for '. Our team knows this rule, but inevitably some messages get the single tick anyway. I was pleased to find out that I could mass-fix this using Eclipse's search and replace feature. I know the search feature supported regexes, but was unaware the replace feature was also regex aware. The trick is I wanted to replace only single ticks, not ticks part of a double tick. The regex for finding these:
[^']{1}'[^']{1}
aka "one non tick followed by a tick, followed by one non-tick"
But to do a replace, I needed to preserve the non-tick values on either side of the tick. Luckily, Eclipse replace understands regex groups. I changed the match to capture the non-ticks:
([^']{1})'([^']{1})
And replaced matches with
$1''$2

I thought that was handy.

On a side note, don't use colons in your key name in a PropertyResourceBundle.
important:Message=Watch out!
Properties parses that as
key = important
value = Message=Watch out!
Properties.load equates ":" with "=". Who knew? Not me.

1 comment:

Charles said...

You can simplify the regex from ([^']{1})'([^']{1}) to ([^'])'([^']). The character classes automatically match one character unless followed by a modifier.