EN
Java - check if string only contains letters
0 points
In this article, we would like to show you how to check if the string only contains letters in Java.
In this example, we use a regular expression (regex) with Pattern.matcher()
to check if the strings contain only letters.
xxxxxxxxxx
1
import java.util.regex.Matcher;
2
import java.util.regex.Pattern;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String letters = "ABCD";
8
String numbers = "1234";
9
String mixed = "a12b";
10
11
String regex = "^[a-zA-Z]+$"; // regex to check if string contains only letters
12
Pattern pattern = Pattern.compile(regex); // compiles the regex
13
14
// find match between given string and pattern
15
Matcher matcherLetters = pattern.matcher(letters);
16
Matcher matcherNumbers = pattern.matcher(numbers);
17
Matcher matcherMixed = pattern.matcher(mixed);
18
19
// return true if the string matched the regex
20
Boolean lettersMatches = matcherLetters.matches();
21
Boolean numbersMatches = matcherNumbers.matches();
22
Boolean mixedMatches = matcherMixed.matches();
23
24
System.out.println(lettersMatches); // true
25
System.out.println(numbersMatches); // false
26
System.out.println(mixedMatches); // false
27
}
28
}
Output:
xxxxxxxxxx
1
true
2
false
3
false
In this example, we create a function that loops through the string and checks if each character is a letter with Character.isLetter(char ch)
method.
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String letters = "ABC";
5
String numbers = "1234";
6
String mixed = "1ab2";
7
8
System.out.println(onlyLetters(letters)); // true
9
System.out.println(onlyLetters(numbers)); // false
10
System.out.println(onlyLetters(mixed)); // false
11
}
12
13
public static boolean onlyLetters(String string) {
14
if (string == null || string.isEmpty()) {
15
return false;
16
}
17
for (int i = 0; i < string.length(); ++i) {
18
if (!Character.isLetter(string.charAt(i))) {
19
return false;
20
}
21
}
22
return true;
23
}
24
}
Output:
xxxxxxxxxx
1
true
2
false
3
false