22

I very new to programming. I want to check if a string s contains a-z characters. I use:

if(s.contains("a") || s.contains("b") || ... {
}

but is there any way for this to be done in shorter code? Thanks a lot

4 Answers4

44

You can use regular expressions

// to emulate contains, [a-z] will fail on more than one character, 
// so you must add .* on both sides.
if (s.matches(".*[a-z].*")) { 
    // Do something
}

this will check if the string contains at least one character a-z

to check if all characters are a-z use:

if ( ! s.matches(".*[^a-z].*") ) { 
    // Do something
}

for more information on regular expressions in java

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Ganesh Krishnan
  • 7,155
  • 2
  • 44
  • 52
mmohab
  • 2,303
  • 4
  • 27
  • 43
  • 1
    Just a clarification: This regex checks if a string contains a-z characters lowercase, if all the alphabetical characters are uppercase, like "STACK20", it'll return false. – Jonathan Cabrera Jun 15 '20 at 05:02
4

In addition to regular expressions, and assuming you actually want to know if the String doesn't contain only characters, you can use Character.isLetter(char) -

boolean hasNonLetters = false;
for (char ch : s.toCharArray()) {
  if (!Character.isLetter(ch)) {
    hasNonLetters = true;
    break;
  }
}
// hasNonLetters is true only if the String contains something that isn't a letter -

From the Javadoc for Character.isLetter(char),

A character is considered to be a letter if its general category type, provided by Character.getType(ch), is any of the following:

UPPERCASE_LETTER
LOWERCASE_LETTER
TITLECASE_LETTER
MODIFIER_LETTER
OTHER_LETTER 
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Use Regular Expressions. The Pattern.matches() method can do this easily. For example:

Pattern.matches("[a-z]", "TESTING STRING a");

If you need to check a great number of string this class can be compiled internally to improve performance.

Dan S
  • 9,139
  • 3
  • 37
  • 48
1

Try this

Pattern p = Pattern.compile("[a-z]");
if (p.matcher(stringToMatch).find()) {
    //...
}
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74