java - 使用包含方法时如何使 IgnoreCase

标签 java

我试图让它在使用包含方法时忽略大小写。我该怎么做?

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/

相关文章:

Java - 序列化 - EOFException 问题

java - 延迟加载 @OneToOne 与 Hibernate 的关系

java - 如何在我的游戏中添加声音字节?

java - Dropwizard 迁移 Liquibase 新变更集未迁移

java - 如何为内部类创建多个实例

Java : Define an enum in a framework (workaround for abstract enum)

java - junit 未找到 Web 应用程序上下文 : no ContextLoad Listener registered?

java - 添加到 Maven 时如何了解码和 Artifact ID

java - Oracle 10g 声称包体有错误但实际上没有

Java PriorityQueue 未轮询预期对象