Java 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
class Main {
public static void main(String[] args) throws Exception {
System.out.println("abc".regionMatches(1, "bc", 0, 2));
}
}
true
Syntax
public boolean regionMatches(int toffset, String other, int ooffset, int len)
JDK 21 method signatures (2)
public boolean regionMatches(int toffset, String other, int ooffset, int len)
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaMatch a carrier code inside a label
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.
class Main {
public static void main(String[] args) throws Exception {
String label = "PK-air-72";
System.out.println(label.regionMatches(true, 3, "AIR", 0, 3));
}
}
true
The three letters after PK- match the carrier code when case is ignored.
Check a fixed-width warehouse field
A printer or scanner accepts a fixed-width field. Compare the space required by the label with the capacity of the destination so a shortened field cannot pass unnoticed.
class Main {
public static void main(String[] args) throws Exception {
String row = "01WEST09";
System.out.println(row.regionMatches(2, "WEST", 0, 4));
}
}
true
The four-character field begins at offset two.
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.