我试图让它在使用包含方法时忽略大小写。我该怎么做?
String text = "Did you eat yet?";
if(text.contains("eat") && text.contains("yet"))
System.out.println("Yes");
else
System.out.println("No.");
最佳答案
不幸的是,String
没有 String.containsIgnoreCase
方法。
但是,您可以使用正则表达式验证类似的条件。
例如:
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());
简单版本(感谢 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.*$"));
输出
true
关于java - 使用包含方法时如何使 IgnoreCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25571551/