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]+$ // Matches alphanumeric Latin characters
Regex: ^\\p{Alnum}+$ // Matches alphanumeric in any locale
^
: Asserts the position at the start of the string.[a-zA-Z0-9]
: Matches any alphanumeric character (i.e., lowercasea
toz
, uppercaseA
toZ
, and digits0
to9
).+
: Matches one or more of the preceding tokens (i.e., one or more alphanumeric characters).$
: Asserts the position at the end of the string.
Use regex “\\p{Alnum}+” to match any alphanumeric character (letters and digits) recognized in any Java Locale.
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 is very easy when you know the basics. Right?
Happy Learning !!
Comments