regionMatches Case Insensitive Regions

regionMatches compares character regions with an offset and an ignoreCase flag, giving allocation-free case-insensitive prefix and infix checks.

JavaSecurity Boundaries

Code

snippet
public class CaseInsensitivePrefix {

    // regionMatches does case-insensitive region comparison without allocations
    static boolean hasPrefix(String value, String prefix, int fromIndex) {
        return value.regionMatches(true, fromIndex, prefix, 0, prefix.length());
    }

    public static void main(String[] args) {
        // Authorization 头/协议前缀的匹配不区分大小写
        System.out.println(hasPrefix("BEARER abc123", "bearer", 0));
        System.out.println(hasPrefix("https://example.com", "HTTP", 0));
        System.out.println(hasPrefix("example.com", "http", 0));

        // 从中部 offset 开始比较:跳过 "user: " 后匹配角色名
        System.out.println(hasPrefix("user: ADMIN", "admin", 6));

        // ignoreCase=false 的对照:大小写敏感返回 false
        System.out.println("sensitive: " + "BEARER abc123".regionMatches(false, 0, "bearer", 0, 6));
    }
}

One method, four arguments, no allocations

hasPrefix(value, prefix, fromIndex) delegates to value.regionMatches(true, fromIndex, prefix, 0, prefix.length()) — ignore-case flag, offset into the value, offset into the prefix, and a length. The comparison walks characters in place, so unlike toLowerCase().startsWith(...) it allocates nothing, which the comment calls out for hot paths like protocol-header matching.

What the five checks print

true
true
false
true
sensitive: false

"BEARER abc123" matches "bearer" from index 0 and "https://example.com" matches "HTTP" — case folding only, never content. "example.com" has nothing to compare at that offset, so it returns false (too short, not a mismatch of letters). The mid-string call hasPrefix("user: ADMIN", "admin", 6) shows the offset parameter skipping "user: " to reach "ADMIN". The final line is the control: the same comparison with ignoreCase=false returns false because BEARER differs from bearer.

The comparison in one call

return value.regionMatches(true, fromIndex, prefix, 0, prefix.length());

The flag true is the only difference from a case-sensitive region check — everything else (offsets, length) is positional.

Interactive Tools for This Topic

FAQ

What does regionMatches Case Insensitive Regions print when run?
The script runs standalone; its 1 labeled outputs include `sensitive:`.