通过使用compile(String regex, int flags)方法创建模式并指定带有PATTERN.CASE_INSENSITIVE常量的第二个参数,可以简单地应用查找与模式匹配的输入序列的下一个子序列,而忽略正则表达式中字符串的情况。
package org.nhooo.example.regex; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexIgnoreCaseDemo { public static void main(String[] args) { String sentence = "The quick brown fox and BROWN tiger jumps over the lazy dog"; Pattern pattern = Pattern.compile("brown", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(sentence); while (matcher.find()) { System.out.format("Text \"%s\" found at %d to %d.%n", matcher.group(), matcher.start(), matcher.end()); } } }
这是程序的结果:
Text "brown" found at 10 to 15. Text "BROWN" found at 24 to 29.