How to check string contains ONLY special characters in Java

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

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

Example >
string '@#!' contains only special character
string '@#!{}$' contains only special character
string '#*^!' contains only special character


string '12@#' doesn't contains only special character
string 'ab@#' doesn't contains only special character
string 'abcd' doesn't contains only special character
string 'ab12' doesn't contains only special character


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

public class StringContainsOnlySpecialCharactersExample {
public static void main(String[] args) {
     String str = "@#!";
     String specialCharacters = "[" + "-/@#!*$%^&.'_+={}()"+ "]+" ;
    
     if ( str.matches(specialCharacters)) {
          System.out.println("string '"+str + "' contains only special character");
     } else {
          System.out.println("string '"+str + "' doesn't contains only special character");
     }
}
}
/*
string '@#!' contains only special character
*/

No comments:

Post a Comment