如何在Java中以不区分大小写的方式检查一个字符串是否包含另一个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/86780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:08:15  来源:igfitidea点击:

How to check if a String contains another String in a case insensitive manner in Java?

javastring

提问by Aaron

Say I have two strings,

假设我有两个字符串,

String s1 = "AbBaCca";
String s2 = "bac";

I want to perform a check returning that s2is contained within s1. I can do this with:

我想执行s2包含在s1. 我可以这样做:

return s1.contains(s2);

I am pretty sure that contains()is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:

我很确定这contains()是区分大小写的,但是我无法通过阅读文档来确定这一点。如果是这样,我想我最好的方法是这样的:

return s1.toLowerCase().contains(s2.toLowerCase());

All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?

抛开这一切不谈,是否有另一种(可能更好)的方法来实现这一点而不关心区分大小写?

采纳答案by Dave L.

Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

是的,包含区分大小写。您可以使用带有 CASE_INSENSITIVE 标志的 java.util.regex.Pattern 进行不区分大小写的匹配:

Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();

EDIT:If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.

编辑:如果 s2 包含正则表达式特殊字符(其中有很多),首先引用它很重要。我已经更正了我的答案,因为它是人们会看到的第一个答案,但是自从他指出这一点以来,请投票给马特奎尔。

回答by SCdF

I'm not sure what your main question is here, but yes, .contains is case sensitive.

我不确定您的主要问题是什么,但是是的, .contains 区分大小写。

回答by Matt Quail

One problem with the answer by Dave L.is when s2 contains regex markup such as \d, etc.

Dave L. 回答的一个问题是当 s2 包含正则表达式标记时,例如\d等。

You want to call Pattern.quote() on s2:

您想在 s2 上调用 Pattern.quote():

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();

回答by Bilbo Baggins

Yes, this is achievable:

是的,这是可以实现的:

String s1 = "abBaCca";
String s2 = "bac";

String s1Lower = s1;

//s1Lower is exact same string, now convert it to lowercase, I left the s1 intact for print purposes if needed

s1Lower = s1Lower.toLowerCase();

String trueStatement = "FALSE!";
if (s1Lower.contains(s2)) {

    //THIS statement will be TRUE
    trueStatement = "TRUE!"
}

return trueStatement;

This code will return the String "TRUE!" as it found that your characters were contained.

此代码将返回字符串“TRUE!” 因为它发现你的角色被包含了。

回答by IVY

String x="abCd";
System.out.println(Pattern.compile("c",Pattern.CASE_INSENSITIVE).matcher(x).find());

回答by Phil

A simpler way of doing this (without worrying about pattern matching) would be converting both Strings to lowercase:

一种更简单的方法(不用担心模式匹配)是将两个Strings都转换为小写:

String foobar = "fooBar";
String bar = "FOO";
if (foobar.toLowerCase().contains(bar.toLowerCase()) {
    System.out.println("It's a match!");
}

回答by muhamadto

You can use

您可以使用

org.apache.commons.lang3.StringUtils.containsIgnoreCase("AbBaCca", "bac");

The Apache Commonslibrary is very useful for this sort of thing. And this particular one may be better than regular expressions as regex is always expensive in terms of performance.

Apache的共享库是这样的事情是非常有用的。这个特殊的可能比正则表达式更好,因为正则表达式在性能方面总是很昂贵。

回答by Shiv

You can use regular expressions, and it works:

您可以使用正则表达式,它可以工作:

boolean found = s1.matches("(?i).*" + s2+ ".*");

回答by Jan Newmarch

I did a test finding a case-insensitive match of a string. I have a Vector of 150,000 objects all with a String as one field and wanted to find the subset which matched a string. I tried three methods:

我做了一个测试,找到了一个不区分大小写的字符串匹配。我有一个包含 150,000 个对象的向量,所有对象都将字符串作为一个字段,并希望找到与字符串匹配的子集。我尝试了三种方法:

  1. Convert all to lower case

    for (SongInformation song: songs) {
        if (song.artist.toLowerCase().indexOf(pattern.toLowercase() > -1) {
                ...
        }
    }
    
  2. Use the String matches() method

    for (SongInformation song: songs) {
        if (song.artist.matches("(?i).*" + pattern + ".*")) {
        ...
        }
    }
    
  3. Use regular expressions

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher("");
    for (SongInformation song: songs) {
        m.reset(song.artist);
        if (m.find()) {
        ...
        }
    }
    
  1. 全部转换为小写

    for (SongInformation song: songs) {
        if (song.artist.toLowerCase().indexOf(pattern.toLowercase() > -1) {
                ...
        }
    }
    
  2. 使用字符串匹配()方法

    for (SongInformation song: songs) {
        if (song.artist.matches("(?i).*" + pattern + ".*")) {
        ...
        }
    }
    
  3. 使用正则表达式

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher("");
    for (SongInformation song: songs) {
        m.reset(song.artist);
        if (m.find()) {
        ...
        }
    }
    

Timing results are:

计时结果为:

  • No attempted match: 20 msecs

  • To lower match: 182 msecs

  • String matches: 278 msecs

  • Regular expression: 65 msecs

  • 未尝试匹配:20 毫秒

  • 降低匹配:182 毫秒

  • 字符串匹配:278 毫秒

  • 正则表达式:65 毫秒

The regular expression looks to be the fastest for this use case.

对于这个用例,正则表达式看起来是最快的。

回答by seth

String container = " Case SeNsitive ";
String sub = "sen";
if (rcontains(container, sub)) {
    System.out.println("no case");
}

public static Boolean rcontains(String container, String sub) {

    Boolean b = false;
    for (int a = 0; a < container.length() - sub.length() + 1; a++) {
        //System.out.println(sub + " to " + container.substring(a, a+sub.length()));
        if (sub.equalsIgnoreCase(container.substring(a, a + sub.length()))) {
            b = true;
        }
    }
    return b;
}

Basically, it is a method that takes two strings. It is supposed to be a not-case sensitive version of contains(). When using the contains method, you want to see if one string is contained in the other.

基本上,它是一个接受两个字符串的方法。它应该是 contains() 的不区分大小写的版本。使用 contains 方法时,您想查看一个字符串是否包含在另一个字符串中。

This method takes the string that is "sub" and checks if it is equal to the substrings of the container string that are equal in length to the "sub". If you look at the forloop, you will see that it iterates in substrings (that are the length of the "sub") over the container string.

此方法采用“sub”字符串并检查它是否等于容器字符串中长度与“sub”相等的子字符串。如果您查看for循环,您将看到它在容器字符串上的子字符串(即“子”的长度)中进行迭代。

Each iteration checks to see if the substring of the container string is equalsIgnoreCaseto the sub.

每次迭代都会检查容器字符串equalsIgnoreCase的子字符串是否属于子字符串。