【问题标题】:How to make IgnoreCase when you're using the contain method [duplicate]使用包含方法时如何制作 IgnoreCase [重复]
【发布时间】: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


    【解决方案1】:

    很遗憾,没有StringString.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) 去除样板文件Patterninfo here
    • @blgt 谢谢,让我改进一下。
    • 我应该把“吃”和“还”放在哪里?
    • 我认为这个答案缺少很多东西。当我试图把它放在 Eclipse 中时,它所做的一切都显示为错误。我是 java 新手,所以如果你不打算把它放在代码中,我不知道你错过了什么。
    • @nmelssx 这个答案要求您导入必要的依赖项,所有这些都在 Java SE 中。在 Eclipse 中,您可以简单地通过按 Ctrl-Shift-O(假设是 Windows)来实现。否则,对 PatternMatcher 的 API 和包进行一些研究应该会对您有所帮助。 “更简单的版本”甚至不需要任何额外的导入。两者都经过测试并在您的问题范围内工作。
    【解决方案2】:

    请使用

     org.apache.commons.lang3.StringUtils.containsIgnoreCase("ABCDEFGHIJKLMNOP", "gHi");
    

    【讨论】:

    • 你需要导入什么吗?
    • 不,因为您使用的是完整路径...
    • 但是我应该把它放在哪里呢?当我尝试将其放入 IF 时出现错误。
    • 我不知道那是什么意思。我是java新手。我只是一个初学者。我不知道 org apache jar 是什么。
    • 对于mena的 System.out.println(text.matches("(?i)^.*\\beat\\b.*\\byet\\b.*$"));如果它是真的,它只会打印出来。你能让它打印别的东西吗?
    猜你喜欢
    • 2015-03-25
    • 2017-03-17
    • 1970-01-01
    • 2013-07-18
    • 2014-06-09
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多