Search

Dark theme | Light theme

November 2, 2009

Groovy Goodness: Remove Parts of a String

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

​def s = 'Groovy and Strings are fun and versatile.'

assert 'Groovy and Strings are fun' == s - ' and versatile.'
assert 'Groovy and Strings are fun.' == s.minus(" and versatile")
assert 'Groovy  Strings are fun and versatile.' == s - ~/\b\w{3}\b/