-3

Is there a way to check if a specific string contains any lower/upper case ?

E.G :

String myStr = "test";
if (myStr.contains("test") { // I would like this condition to 
                                check the spell of "test", weather it is
                                written like "Test" or "teSt" etc...
//Do stuff
}

With this syntax, it works only for the exact same string. How could I make my condition for anyform of "test", like : "Test", "tEst", "tesT" etc... ?

Beginner
  • 161
  • 4
  • 12

6 Answers6

1

You can use equalsIgnoreCase() method. This method compares two String with ignoring the case.

String a = "Test";

if("test".equalsIgnoreCase(a)) //returns true
{ 
  //do stuff
}
dpaksoni
  • 327
  • 3
  • 17
0

Force the haystack (the string in which you search) to lower case and then search for the lowercase needle (the string you search)

myStr.toLowerCase().contains("test")
loonytune
  • 1,775
  • 11
  • 22
0

How about transforming myStr to lower case and check after. Something like this:

String myStr = "test";
if (myStr.toLowerCase().contains("test") { 
      //Do stuff
}
alexandrum
  • 429
  • 9
  • 17
  • The question was checking whether a string contains "any" lowercase characters. But, your answer checks whether the whole string is lowercase. – Salih Kavaf Mar 18 '21 at 20:06
0

You can use this regex to check if a String contains any uppercase letters.

String regex = ".*[A-Z].*";
if (myStr.matches(regex)) {
   // Write your code here
}
dnguyen
  • 149
  • 1
  • 2
  • 12
-1

You can use a regex like this [a-z]+ This will check if there is a lowercase character from a-z

Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("tEST");
if(m.matches()) {
// string contains lowercase
}
0riginal
  • 137
  • 1
  • 11
-1

Solution :

String name1="test";

System.out.println(name1.toLowerCase().equals(name1));    //true
System.out.println(name1.toUpperCase().equals(name1));    //false

The logic is if the first statement is true it means the string has only lower case letters. if the second statement is true it means the string has only upper case letters. if both are false it means that it has a mixture of both.

User27854
  • 824
  • 1
  • 16
  • 40