Java - Ignore case checking user input

10,438

Solution 1

You can temporarily convert both strings into lowercase or both into uppercase and then do the matching.

for(int i=0;i<myList.length-1;i++){
       if(myString.toLowerCase().contains(myList.get(i).toLowerCase())){
           // your code if myString is contained within a String in the List
       }
}

or

for(int i=0;i<myList.length-1;i++){
       if(myString.toUpperCase().contains(myList.get(i).toUpperCase())){
           // your code if myString is contained within a String in the List
       }
}

Solution 2

You can try Pattern.CASE_INSENSITIVE with the Pattern.

Solution 3

I don't understand why you can't use String.equalsIgnoreCase(). Regex is not needed for this. If you use a List, you can use .stream().anyMatch() with this Predicate:

c -> c.equalsIgnoreCase(data)

Code Sample:

public static void main(String[] args) throws Exception {
    List<String> check = new ArrayList() {{
        add("dog");  
        add("CAT");
        add("oWl");
        add("GiraFFe");
    }};

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter data: ");
    String data = scanner.nextLine();

    if (check.stream().anyMatch(c -> c.equalsIgnoreCase(data))) {
        System.out.println("Data found");
    } else {
        System.out.println("Data not found");
    }
}

Results:

Enter data: gIRAffE
Data found

Enter data: lamb
Data not found
Share:
10,438
Dom
Author by

Dom

Updated on June 04, 2022

Comments

  • Dom
    Dom almost 2 years

    I need to check if the user input matches anything in a Set or List, but I am currently using .contains(). Obviously this is not working when the user inputs something that is not the correct case, so I was thinking of using .matches( regex ), but am not a professional regexer.

    Would could I use Regex or Pattern to check if the user input matches anything in a List, case aside.

    Thank you.

    I did just notice that I will have to use a for-loop to get the elements out of my Set before comparing them with .matches().

  • Shar1er80
    Shar1er80 over 8 years
    Why bother upper/lower casing when you can just use String.equalsIgnoreCase()?
  • RoHaN
    RoHaN over 8 years
    String.equalsIgnoreCase() checks whether that it is that actual string not more not less. we need contains to check whether that it contains the string not equals to the exact string.
  • David Veszelovszki
    David Veszelovszki over 8 years
    String.equalsIgnoreCase() checks whether that it is the full string. OP needs contains() to check if it contains the string, not equals to it.