Tell If String Contains a-Z Chars [Duplicate]
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...
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
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
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
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.
Try this
Pattern p = Pattern.compile("[a-z]");
if (p.matcher(stringToMatch).find()) {
//...
}