Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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?

like image 348
Aaron Avatar asked Sep 17 '08 19:09

Aaron


People also ask

How do you check if a string contains another string in a case insensitive manner in Python?

Ignore case : check if a string exists in another string in case insensitive approach. Use re.search() to find the existence of a sub-string in the main string by ignoring case i.e. else return a tuple of False & empty string.

Does string contain check case insensitive Java?

Yes, contains is case sensitive. You can use java. util.

How do you do case insensitive string comparison in Java?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.


2 Answers

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.

like image 150
Dave L. Avatar answered Sep 22 '22 17:09

Dave L.


One problem with the answer by Dave L. is when s2 contains regex markup such as \d, etc.

You want to call Pattern.quote() on s2:

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find(); 
like image 24
Matt Quail Avatar answered Sep 24 '22 17:09

Matt Quail