Loading...

Thursday, 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()

3 comments:

Best Business Brands said...

Groovy is a great language to write DSL implementations. The Groovy syntax allows for example to leave out parenthesis or semi colons, which ...

Павел Алексеев said...

"or if it matches the first part of the pattern"
It is not clear what you mean under "parts of the pattern" there. Could you please explain slightly more?

Hubert Klein Ikkink said...

@Павел Алексеев: Normally a String value needs to match the whole pattern to get a true value. With this method the pattern matching is more forgiving. If we now check a String value against the pattern not the whole String value needs to match, but also a shorter String value can match the pattern.

Post a Comment