Search

Dark theme | Light theme

June 28, 2012

Groovy Goodness: Partial Matches

Groovy 2.0 adds the matchesPartially() method to the Matcher class. This method returns true if a String value matches the pattern or if it matches the first part of the pattern. So with the matchesPartially() we get the result true if a String value or a longer String value matches the pattern.

def identification = /[A-Z]{2}\-\d{3,5}/

def matcher = 'AB-1234' =~ identification
assert matcher.matchesPartially()

matcher = 'XY-90' =~ identification
assert matcher.matchesPartially()

matcher = 'HA' =~ identification
assert matcher.matchesPartially()

matcher = 'A-431' =~ identification
assert !matcher.matchesPartially()

matcher = 'YK-901201' =~ identification
assert !matcher.matchesPartially()