- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to check if a string contains any special character
To check if a string contains any special character, the Java program is as follows −
Example
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.
Advertisements