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)
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
Modify the Regular expression from [a-zA-Z0-9]
to ^[a-zA-Z0-9]+$
String text="abcABC983";
System.out.println(text.matches("^[a-zA-Z0-9]+$"));
Current output: true
The regular expression character class \\p{Alnum}
can be used in conjunction with String#matches
. It is equivalent to [\\p{Alpha}\\p{Digit}]
or [a-zA-Z0-9]
.
boolean allLettersAndNumbers = str.matches("\\p{Alnum}*");
// Change * to + to not accept empty String
See the Pattern
documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.