Friday, March 1, 2019

java - How to make IgnoreCase when you're using the contain method




I'm trying to make it ignore the cases, while using the contain method. How do I do that?



String text = "Did you eat yet?";   

if(text.contains("eat") && text.contains("yet"))
System.out.println("Yes");
else
System.out.println("No.");


Answer



Unfortunately there's no String.containsIgnoreCase method of String.



However, you can verify a similar condition with regular expressions.



For instance:



String text = "Did you eat yet?";
// will match a String containing both words "eat",

// then "yet" in that order of appearance, case-insensitive
// | word boundary
// | | any character, zero or more times
Pattern p = Pattern.compile("\\beat\\b.*\\byet\\b", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
System.out.println(m.find());


Simpler version (thanks blgt):




// here we match the whole String, so we need start-of-input and 
// end-of-input delimiters
// | case-insensitive flag
// | | beginning of input
// | | | end of input
System.out.println(text.matches("(?i)^.*\\beat\\b.*\\byet\\b.*$"));


Output




true

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...