13

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)
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
unclesam
  • 149
  • 1
  • 1
  • 4
  • 3
    Option 1: loop through the string and check each character individually. Option 2: regular expressions: `name.matches("[a-zA-Z0-9]*");` - assuming you mean normal letters, not accented characters or anything like that. – khelwood Nov 01 '15 at 21:41
  • Possible duplicate of [How to check if a string is numeric?](http://stackoverflow.com/questions/14206768/how-to-check-if-a-string-is-numeric) – Yassin Hajaj Nov 01 '15 at 21:41

4 Answers4

22

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

Harsh Poddar
  • 2,394
  • 18
  • 17
5
  1. Use regular expressions :

    Pattern pattern = Pattern.compile("\\p{Alnum}+");
    Matcher matcher = pattern.matcher(name);
    if (!matcher.matches()) {
        // found invalid char
    }
    
  2. 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

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
4

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

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
0

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80