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 !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode