In this post we will learn how to check string contains only alphabets/letters using regex (regular expression) and apache commons StringUtils class in java.
Regular expressions provides one of the simplest ways to find whether string contains only alphabets/letters or not in java.
Example >
string 'abcd' contains only alphabets/letters
string 'abqu' contains only alphabets/letters
string 'ab12' doesn't contains only alphabets/letters value
string 'ab@' doesn't contains only alphabets/letters value
Example 1 to check string contains only alphabets/letters in java using regex >
regex (Regular Expression) used = "[a-zA-Z]+"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsOnlyAlphabetsExample1 {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[a-zA-Z]+");
String str = "abcd";
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println("string '"+str + "' contains only alphabets/letters");
} else {
System.out.println("string '"+str + "' doesn't contains only alphabets/letters value");
}
}
}
/*
string 'abcd' contains only alphabets/letters value
*/
|
Example 2 to check string contains only alphabets/letters in java using org.apache.commons.lang.StringUtils.isAlpha(str) >
import org.apache.commons.lang.StringUtils;
public class StringContainsOnlyAlphabetsExample2_UsingCommons {
public static void main(String[] args) {
String str = "abcd";
System.out.println(StringUtils.isAlpha(str));
}
}
/*
true
*/
|
Jar used in above program = commons-lang.jar