How to check string contains special characters in Java

In this post we will learn how to check string contains special characters using regex (regular expression) in java.

Regular expressions provides one of the simplest ways to find whether string contains special characters or not in java.

Example >
string 'abc@' contains special character
string '1#23' contains special character
string '1#@a' contains special character
string '%&#@' contains special character


string 'abc' doesn't contains special character
string 'abc12' doesn't contains special character
string '123' doesn't contains special character


Example to check string contains special characters in java using regex >

Any string that doesn’t matches regex "[a-zA-Z0-9]*" contains special characters.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsSpecialCharactersExample {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile("[a-zA-Z0-9]*");
     String str = "abc@";
     Matcher matcher = pattern.matcher(str);
     if (!matcher.matches()) {
          System.out.println("string '"+str + "' contains special character");
     } else {
          System.out.println("string '"+str + "' doesn't contains special character");
     }
}
}
/*
string 'abc@' contains special character
*/

No comments:

Post a Comment