【发布时间】:2014-10-23 15:48:38
【问题描述】:
我试图让它忽略这些情况,同时使用包含方法。我该怎么做?
String text = "Did you eat yet?";
if(text.contains("eat") && text.contains("yet"))
System.out.println("Yes");
else
System.out.println("No.");
【问题讨论】:
标签: java
我试图让它忽略这些情况,同时使用包含方法。我该怎么做?
String text = "Did you eat yet?";
if(text.contains("eat") && text.contains("yet"))
System.out.println("Yes");
else
System.out.println("No.");
【问题讨论】:
标签: java
很遗憾,没有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
【讨论】:
?i 标志的String.matches(regex) 去除样板文件Pattern,info here
Pattern 和 Matcher 的 API 和包进行一些研究应该会对您有所帮助。 “更简单的版本”甚至不需要任何额外的导入。两者都经过测试并在您的问题范围内工作。
请使用
org.apache.commons.lang3.StringUtils.containsIgnoreCase("ABCDEFGHIJKLMNOP", "gHi");
【讨论】: