实现说明
底层就是类 CaseInsensitivePrefix和函数 hasPrefix、main。
使用要点
- 跑完文件,输出里会留下标记——
sensitive:。 main按顺序串起hasPrefix;运行文件就会把这个流程跑一遍。
常见问题
运行「regionMatches 忽略大小写的区域比较」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 sensitive: 标签标明各步骤。
签名一览:static boolean hasPrefix(String value, String prefix, int fromIndex)
核心语句
return value.regionMatches(true, fromIndex, prefix, 0, prefix.length());
代码示例
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));
}
}