You can use
org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
CharSequence searchStr);
Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).
A null CharSequence will return false.
This one will be better than regex as regex is always expensive in terms of performance.
For official doc, refer to : StringUtils.containsIgnoreCase
Update :
If you are among the ones who
regex/Pattern
based solutions, toLowerCase
, you can implement your own custom containsIgnoreCase
using java.lang.String.regionMatches
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
ignoreCase
: if true, ignores case when comparing characters.
public static boolean containsIgnoreCase(String str, String searchStr) {
if(str == null || searchStr == null) return false;
final int length = searchStr.length();
if (length == 0)
return true;
for (int i = str.length() - length; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, length))
return true;
}
return false;
}
If you won't go with regex:
"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())
You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}
An optimized Imran Tariq's version
Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();
Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.
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