How to check if a String contains another String in a case insensitive manner in Java?

前端 未结 19 1457
渐次进展
渐次进展 2020-11-22 03:20

Say I have two strings,

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

I want to perform a check returning that s2 is contained

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:00

    Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

    Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
    

    EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.

提交回复
热议问题