VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-match-regions-in-strings-in-java/

⇱ Java String regionMatches() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java String regionMatches() Method

Last Updated : 23 Jul, 2025

In Java, regionMatches() method of the String class compares parts (regions) of two strings to see if they match. It offers both case-sensitive and case-insensitive comparison options. This method is commonly used in string matching and validation tasks in the Java programming.

Example:


Output
true

Explanation: In the above example, the method compares a region of s1 starting from index 7 with s2 starting from index 0. It checks if the first 7 characters of s1 match with s2, and the result is true because "welcome" in s1 matches s2.

Syntax of regionMatches() Method

1. Case-sensitive comparison:

public boolean regionMatches(int toffset, String other, int offset, int len)

2. Case-insensitive comparison:

public boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)

Parameters:

  • ignoreCase: If true, the comparison ignores case sensitivity.
  • toffset: The starting offset of the subregion in the first string (this).
  • other: The second string to compare against.
  • offset: The starting offset of the subregion in the second string.
  • len: The length of the substring to compare.

Return Value: The method returns true if the substrings of both strings, starting from the given offsets and of the specified length, are equal. The comparison is case-sensitive unless ignoreCase is true.

Example 1: Case-Sensitive Comparison


Output
Result: true
Result: false
Result: false

Explanation: In the above example, the s1.regionMatches(11, s2, 0, 13) compares characters from index 11 of s1 with the first 13 characters of s2. It returns true because the substrings match. The s1.regionMatches(11, s3, 0, 13) compares the substrings, but case differences cause it to return false. The s2.regionMatches(0, s3, 0, 13) also returns false due to case differences.

Example 2: Case-Insensitive Comparison


Output
Result: true
Result: false
Result: true

Explanation: In this example, s1.regionMatches(true, 0, s2, 0, 3) compares "Java" and "java" (ignoring case), returning true. The s1.regionMatches(false, 0, s3, 0, 3) compares "Java" and "JAVA" (case-sensitive) and returns false. Finally, s2.regionMatches(true, 0, s3, 0, 3) compares "java" and "JAVA" (ignoring case) and returns true.

Comment