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