Regex for Alphanumeric Characters (+ Example)

To create a regular expression that allows only alphanumeric characters, we can use the regex pattern ^[a-zA-Z0-9]+$. This pattern ensures that the string consists solely of uppercase alphabets, lowercase alphabets, and digits.

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]+$

  • ^: Asserts the position at the start of the string.
  • [a-zA-Z0-9]: Matches any alphanumeric character (i.e., lowercase a to z, uppercase A to Z, and digits 0 to 9).
  • +: Matches one or more of the preceding tokens (i.e., one or more alphanumeric characters).
  • $: Asserts the position at the end of the string.

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.