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?
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.
Yes, contains is case sensitive. You can use java. util.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With