RegEx

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

How to allow only alphanumeric characters in string using a-zA-Z0-9 pattern?

Regular expression 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 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 following pattern should be used.

How to remove special characters from String using regular expressions in Java?

The similar pattern can be used to remove unwanted characters from 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 replaceAll() method of string instead of matches() method.

We are going to use following pattern to remove all special characters from the String.

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

Output

See Also:

Please let us know your views in the comments section below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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