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-Z
or 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 groupa-z
: any lowercase letterA-Z
: any uppercase letter0-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]+$
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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
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?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.