Java program to check if a string contains any special character

JavaServer Side ProgrammingProgramming

To check if a string contains any special character, the Java program is as follows −

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String[] args){
      String my_str="This is a sample only !$@";
      Pattern my_pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
      Matcher my_match = my_pattern.matcher(my_str);
      boolean check = my_match.find();
      if (check)
         System.out.println("Special character found in the string");
      else
         System.out.println("Special character not found in the string");
   }
}

Output

Special character found in the string

A class named Demo contains the main function, where a string is defined, with some special characters. A pattern is defined that uses regular expressions to check if the string has any special characters. A Boolean value is defined, that checks to see for the same. If the value of Bool is true, a success message is printed, otherwise, a message stating the absence of these special characters is printed on the screen.

raja
Published on 13-Jul-2020 15:49:19
Advertisements