Java Alphanumeric Regex Example

This Java example demonstrates how to write a regular expression to validate user input in such a way that it allows only alphanumeric characters. Alphanumeric characters are all alphabets and numbers i.e. letters A–Z, a–z, and digits 0–9.

Java Alphanumeric Regex Example

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestDemo {
    public static void main(String[] args) {
        List < String > names = new ArrayList < String > ();

        names.add("SourceCodeExample");
        names.add("SourceCodeExample123");
        names.add("SourceCodeExample-----////"); //Incorrect

        String regex = "^[a-zA-Z0-9]+$";

        Pattern pattern = Pattern.compile(regex);

        for (String name: names) {
            Matcher matcher = pattern.matcher(name);
            System.out.println(matcher.matches());
        }
    }
}
Output:
true
true
false






Comments