[wp-night-mode-button]

Java Regex for alphanumeric characters

In this post, we will see how to create regex alphanumeric which will create only alphanumeric characters.
There are times when you need to validate the user’s input. It should contain only characters from a-z, A-Zor 0-9.
Here is simple regex for it.

^[a-zA-Z0-9]*$

Here is the explaination of above regex.

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
]: end of character group
* : zero or more of the given characters
$ : end of string

If you do not want to allow empty string, you can use + instead of *.

^[a-zA-Z0-9]+$
Java program to test regex alphanumeric characters.

package org.arpit.java2blog;

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

public class RegexExample {

    public static void main(String args[])
    {
        List<String> listOfUserNames=new ArrayList<>();
        listOfUserNames.add("Java2blog");
        listOfUserNames.add("Java-2-blog");
        listOfUserNames.add("Java2blog Tutorials");
        listOfUserNames.add("Java2blogTutorials");
        listOfUserNames.add("");

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

        Pattern pattern = Pattern.compile(regex);

        for (String name : listOfUserNames)
        {
          Matcher matcher = pattern.matcher(name);
          System.out.println("Only Alphanumeric in "+name+" : "+ matcher.matches());
        }
    }
}

Output

Only Alphanumeric in Java2blog : true
Only Alphanumeric in Java-2-blog : false
Only Alphanumeric in Java2blog Tutorials : false
Only Alphanumeric in Java2blogTutorials : true
Only Alphanumeric in : true

That’s all about Java Regex – alphanumeric characters

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.