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

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

Was this post helpful?

Leave a Reply

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