OneBite.Dev - Coding blog in a bite size

check if a string contains only letters in java

Code snippet on how to check if a string contains only letters in java

String input = "Hello World"; 
boolean onlyLetters = input.matches("[A-Za-z]+");

This code uses the matches() method to check if a string contains only letters. The input variable is set to “Hello World”, and the onlyLetters boolean variable is used to store the result of the expression. [A-Za-z]+ is a regular expression to match any characters from A to Z in upper and lower case. If the input string does not contain any special characters except for letters, the expression will be true, otherwise it will be false.

java