Groovy String.regionMatches
Compare selected ranges in two strings without extracting either substring.
A simple example
String.regionMatches
- Start with "abc" from its second character
- Do this Compare that region with "bc"
- Result Match
Syntax
public boolean regionMatches(int toffset, String other, int ooffset, int len)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCheck part of a parcel label
A parcel label has a carrier field between other characters. Compare just the expected range to identify the carrier while leaving the rest of the routing label untouched.
println "PK-air-17".regionMatches(true, 3, "AIR", 0, 3)
true
Three letters match without extracting the field.
Detect a short import field
A shipping or campus label contains several fields with fixed boundaries. Match only the selected field and allow for short input that might end before all expected characters are present.
println "PK-A".regionMatches(3, "AIR", 0, 3)
false
The input ends before the expected field does.
Check a carrier field
A sample label puts the carrier code after the depot name. Compare the two-letter field beginning immediately after the first hyphen with AX. Does the carrier field match?
What to watch for
The comparison length counts UTF-16 units. A range that does not fit yields false.