Tell if string contains a-z chars

user2276872 picture user2276872 · Jun 6, 2014 · Viewed 73.3k times · Source

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

Answer

mmohab picture mmohab · Jun 6, 2014

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