Search

Dark theme | Light theme

June 15, 2010

Groovy Goodness: Text Translation

In Groovy 1.7.3 the tr() method is added to the String class. With this method we can do translations in String values. We define a source set of characters that need to be replaced by a replacement set of characters. We can also use a regular expression style (remember it is not a real regular expression) to define a range of characters.

If the replacement set is smaller than the source set, than the last character of the replacement set is used for the remaining source set characters.

// Source set and replacement set are equal size.
assert 'I 10v3 9r00vy' == 'I love Groovy'.tr('loeG', '1039')

// Regular expression style range
assert 'mrHAKI' == 'mrhaki'.tr('a-k', 'A-K')

// Replacement set is smaller than source set.
assert 'Gr8888' == 'Groovy'.tr('ovy', '8')