This example will show you how to allow only alphanumeric characters in a string using the a-zA-Z0-9 regular expression pattern. It also shows how to remove special characters from the string.
How to allow only alphanumeric characters in a string using an a-zA-Z0-9 pattern?
The below given regular expression pattern can be used to check if the string contains only alphanumeric characters or not.
1 |
String strPattern = "^[a-zA-Z0-9]*$"; |
1 2 3 4 5 6 7 |
Where ^ - start of the String a-z - any character between a and z A-Z - any character between A and Z 0-9 - any digit between 0 and 9 * - 0 or more instances and $ - end of String |
Let’s see the pattern in action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.javacodeexamples.regex; public class AlphanumericCharExample { public static void main(String args[]){ String strPattern = "^[a-zA-Z0-9]*$"; String inputString1 = "StringWithSpecialCharacters,Numbers01And@Symbol"; String inputString2 = "01AlphanumericString"; if(inputString1.matches(strPattern)) System.out.println(inputString1 + ": is alphanumeric"); else System.out.println(inputString1 + ": is not alphanumeric"); if(inputString2.matches(strPattern)) System.out.println(inputString2 + ": is alphanumeric"); else System.out.println(inputString2 + ": is not alphanumeric"); } } |
Output
1 2 |
StringWithSpecialCharacters,Numbers01And@Symbol: is not alphanumeric 01AlphanumericString: is alphanumeric |
Note: The pattern is given in the example (a-zA-Z0-9) only works with ASCII characters. It fails to match the Unicode characters.
If the application needs Unicode characters compatible pattern matching, then the following pattern should be used.
1 |
String strPattern = "^[\\pL\\pN]*$"; |
1 2 3 |
Where, \pL – match any letter \pN – match any number |
How to remove special characters from the string using a regular expression?
A similar pattern can be used to remove unwanted characters from the string as well. For example, if you want to remove everything but the alphabets and numbers from the string, you can use the same pattern but with the replaceAll
method of string instead of the matches
method.
We are going to use the following pattern to replace all special characters with the empty string.
1 |
String strPattern = "[^a-zA-Z0-9]"; |
It means match any character which is not between a to z, A to Z and 0 to 9.
1 2 3 4 5 |
String strPattern = "[^a-zA-Z0-9]"; String inputString1 = "StringWithSpecialCharacters,Numbers01And@Symbol"; inputString1 = inputString1.replaceAll(strPattern, ""); System.out.println(inputString1); |
Output
1 |
StringWithSpecialCharactersNumbers01AndSymbol |
See Also:
- How to keep only letters in String?
- How to keep only numbers in String?
- How to keep only letters and numbers String?
This example is a part of the Java String tutorial and Java RegEx tutorial.
Please let me know your views in the comments section below.