Thursday, December 27, 2018

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



Say I have two strings,




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


I want to perform a check returning that s2 is contained within s1. I can do this with:



return s1.contains(s2);



I am pretty sure that contains() is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:



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


All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...