In this post, we will know how to check if a string contains a special character in Java.

So we need to write a Java program which outputs whether or not the string contains any special character. Example

So let’s see how we can do that in Java.

Method 1: Using Java Regex

The Java Regex or Regular Expression is used to define the pattern to search or manipulate strings.

We usually define a regex pattern in the form of string eg “[^A-Za-z0-9 ]” and use Java Matcher to match for the pattern in the string.

“[A-Za-z0-9 ]” will match strings made up of alphanumeric characters only (blank space inclusive).

“[^A-Za-z0-9 ]” will match strings made up of characters others than alphanumeric and blank spaces i.e special characters.

So if the input string matches “[^A-Za-z0-9 ]” pattern it means it contains at least one character.

Let’s implement the regex in Java and see how actually it can be used to check for special characters.

output

Java output for special character check

Note: [^A-Za-z0-9] pattern return true when string contains a blank space so we have excluded blank space from the pattern using [^A-Za-z0-9 ].

Method 2: Using Brute Force

In this method we specify all possible special characters into a single string, then we check if any special character is present in the input string.

For this, we will use contain() method of string class.

output

java output 2 for special character check

See how easy it was to code in Java. If you have any suggestions or doubts then please comment below.

Leave a Reply