Java regex to allow only alphanumeric characters

We can use the given regular expression used 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.

1. Alphanumeric regex pattern

With alphanumeric regex at our disposal, the solution is dead simple. A character class can set up the allowed range of characters. With an added quantifier that repeats the character class one or more times, and anchors that bind the match to the start and end of the string, we’re good to go.

Regex: ^[a-zA-Z0-9]+$

2. Alphanumeric regex example

List<String> names = new ArrayList<String>();
      
names.add("Lokesh");  
names.add("LOkesh123");  
names.add("LOkesh123-");  //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());
}

Program Output.

true
true
false

It’s very easy when you know the basics. Right?

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.