温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java regex怎么忽略大小写

发布时间:2026-10-04 22:32:15 来源:亿速云 阅读:91 作者:小樊 栏目:编程语言

在 Java 中,使用正则忽略大小写有几种常见方式:

1. 使用 (?i) 内联标志(推荐,最灵活)

在正则表达式中加入 (?i) 即可忽略大小写:

String regex = "(?i)hello";
System.out.println("HELLO".matches(regex)); // true

也可以只针对部分内容忽略大小写:

String regex = "abc(?i)def"; // 只有 def 忽略大小写

2. 使用 Pattern.CASE_INSENSITIVE 标志

import java.util.regex.*;

Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("HELLO");
System.out.println(matcher.matches()); // true

如果是 Unicode 字符(如中文、德文等),建议加上:

Pattern.compile("hello", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);

3. String 的 matches / replaceAll 等

String 的方法不支持直接传标志,但可以用内联 (?i):

"HELLO".matches("(?i)hello"); // true
"HELLO".replaceAll("(?i)hello", "hi"); // "hi"

总结

  • ✅ 简单场景:"(?i)regex"
  • ✅ 复杂/复用:Pattern.compile(regex, Pattern.CASE_INSENSITIVE)

如果你有具体代码场景(比如提取、替换、校验),可以发出来我帮你写。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手