假设我有两个字符串,

String s1 = "AbBaCca";
String s2 = "bac";

我想执行一个检查,返回s2包含在s1中。我可以这样做:

return s1.contains(s2);

我非常确定contains()是区分大小写的,但是我不能从阅读文档中确定这一点。如果是的话,我想我最好的方法是:

return s1.toLowerCase().contains(s2.toLowerCase());

撇开所有这些不谈,有没有另一种(可能更好的)方法可以在不考虑大小写敏感性的情况下完成这个任务?


当前回答

你可以使用正则表达式,它工作:

boolean found = s1.matches("(?i).*" + s2+ ".*");

其他回答

Dave L.回答的一个问题是s2包含正则表达式标记,如\d等。

你想在s2上调用Pattern.quote():

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();

有一个简单简洁的方法,使用regex标志(不区分大小写{i}):

 String s1 = "hello abc efg";
 String s2 = "ABC";
 s1.matches(".*(?i)"+s2+".*");

/*
 * .*  denotes every character except line break
 * (?i) denotes case insensitivity flag enabled for s2 (String)
 * */

你可以使用

org.apache.commons.lang3.StringUtils.containsIgnoreCase("AbBaCca", "bac");

Apache Commons库对于这类事情非常有用。这个特殊的表达式可能比正则表达式更好,因为正则表达式在性能方面总是代价高昂。

String x="abCd";
System.out.println(Pattern.compile("c",Pattern.CASE_INSENSITIVE).matcher(x).find());

你可以使用正则表达式,它工作:

boolean found = s1.matches("(?i).*" + s2+ ".*");