Library contents

Java 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.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("abc".regionMatches(1, "bc", 0, 2));
    }
}
Output
true

Syntax

Java 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.java

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

From the programString label = "PK-air-72"
Resulttrue
Main.java
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));
    }
}
Output
true

The three letters after PK- match the carrier code when case is ignored.

Advertisements

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.

From the programString row = "01WEST09"
Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String row = "01WEST09";
        System.out.println(row.regionMatches(2, "WEST", 0, 4));
    }
}
Output
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?

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