Skip to content

Java RegEx – Check Special Characters in String

Java RegEx – Check Special Characters in String example shows various ways to check if the string contains any special characters using Java regular expression patterns.

How to check if a string contains special characters using regex?

There are various ways in which you can check it in Java. If you are sure about what all characters you do not want to allow, defining a character class that includes all those characters gets the job done.

For example, if you want to check for special characters “~!@#$%^&*()_+{}[]:;,.<>/?-” then it can be included in the regex pattern quite easily as given below.

I created a character class using the square brackets and specified all the characters I want to check inside it. The start and end bracket needs to be escaped inside the character class. Similarly, if you want to specify “-” (hyphen), then it cannot be in the middle unless you want to specify a range like a-z or A-Z.

Here is the example code that checks for the specified special characters in regex. It also shows how to remove them from the string using the replaceAll method using same regex.

Output

Is this a suggested way to check special characters?

NO. As you can see from the output, the code worked fine. However, this is not a suggested approach. Why? because there are characters that are not there on the keyboard, but you still want to check for that. For example, Unicode characters, or characters with accents like “àèìòù”.

It can be very difficult for you to list out all the special characters you do not want to allow. Instead of specifying what you do not want to allow, listing what you want to allow is so much easier. For example, you want to allow only alphanumeric characters and an underscore.

Writing a regex pattern for that is so much easier. Here is the regex for that.

Where

The above regex will allow characters from a to z, A to Z, digits 0 to 9, and an underscore. It basically matches with all the special characters except for the underscore. Let’s try this regex.

Output

We got the same output, except for the inclusion of the underscore, but this time the pattern is so much easier to read and maintain.

You can add more characters to the character class that you want to allow. For example, if you want to ignore space, you can include that in the regex as given below.

The “\s” is a space character in regex.

If you want to learn more about regex, visit the 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.