Skip to content

Allow only alphanumeric characters using a-zA-Z0-9 Java regular expression

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.

Let’s see the pattern in action.

Output

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.

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.

It means match any character which is not between a to z, A to Z and 0 to 9.

Output

See Also:

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.

About the author

Leave a Reply

Your email address will not be published.