Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Java program to check if a string contains any special character
In Java, checking if a string contains special characters can be easily done using regular expressions. We will be using the Pattern and Matcher classes from the java.util.regex package, we can efficiently determine whether a string includes any special characters. In this article, we will demonstrate how to use these classes to perform the check and handle the result accordingly. ?
Problem Statement
For a given string write a Java program to check if it contains any special character or not ?
Input 1
I Love Tutorialspoint
Output 1
Special character not found in the string
Input 2
This is a sample only !$@
Output 2
Special character found in the string
Step to check if a string contains any special character
Following are the steps to check if a string contains any special character ?
- Import the Pattern and Matcher classes from the java.util.regex package.
- Initialize a string that may or may not contain special characters.
- Use Pattern.compile() to create a pattern that identifies special characters.
- Create a Matcher object and use the find() method to check for any special characters in the string.
- Print a message depending on whether special characters are found.
Java program to check if a string contains any special character
Below is the Java program to check if a string contains any special characters ?
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
Code Explanation
A class named Demo contains the main function, where a string is defined, with some special characters. A pattern that uses regular expressions to check if the string has any special characters is described. A Boolean value is specified, 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.
