Library contents

Groovy String.regionMatches

Compare selected ranges in two strings without extracting either substring.

A simple example

String.regionMatches

  1. Start with "abc" from its second character
  2. Do this Compare that region with "bc"
  3. Result Match
The two characters from the chosen position are b and c.

Syntax

Groovy 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.groovy

Check 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.

Resulttrue
Lesson.groovy
println "PK-air-17".regionMatches(true, 3, "AIR", 0, 3)
Output
true

Three letters match without extracting the field.

Advertisements

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.

Resultfalse
Lesson.groovy
println "PK-A".regionMatches(3, "AIR", 0, 3)
Output
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?

GivenN-AX04 · expected AX
Worked resultMatch

What to watch for

The comparison length counts UTF-16 units. A range that does not fit yields false.

Documentation for String.regionMatches