In this Java program we will learn how to check the string contains special characters in java using regex .
Regular expressions provides one of the simplest ways to find whether string contains special characters.
Java Program to check string contains special characters in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindSpecialCharacter
{
public int getSpecialCharacter(String str)
{
if (str == null || str.trim().isEmpty()) {
System.out.println("format of string is Incorrect ");
return 0;
}
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher matcher = pattern.matcher(str);
boolean b = matcher.find();
if (b == true)
System.out.println("There is a special character in my string:- " + str);
else
System.out.println( "There is no special character in my String :- " + str);
return 0;
}
public static void main(String[] args)
{
FindSpecialCharacter FSC =new Main();
String str ="Tutorialspoint4all.com";
FSC.getSpecialCharacter(str);
}
}
After execution of above program you will get the output like below:-
