Let's say a user inputs text. How does one check that the corresponding String
is made up of only letters and numbers?
import java.util.Scanner;
public class StringValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your password");
String name = in.nextLine();
(inert here)
To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.
In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0. The isalpha() function is defined in <ctype. h> header file.
You can call matches
function on the string object. Something like
str.matches("[a-zA-Z0-9]*")
This method will return true if the string only contains letters or numbers.
Tutorial on String.matches: http://www.tutorialspoint.com/java/java_string_matches.htm
Regex tester and explanation: https://regex101.com/r/kM7sB7/1
Use regular expressions :
Pattern pattern = Pattern.compile("\\p{Alnum}+");
Matcher matcher = pattern.matcher(name);
if (!matcher.matches()) {
// found invalid char
}
for loop and no regular expressions :
for (char c : name.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
// found invalid char
break;
}
}
Both methods will match upper and lowercase letters and numbers but not negative or floating point numbers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With