Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check that the String does not contain certain characters in Java
Let’s say the following is our string with special characters.
String str = "test*$demo";
Check for the special characters.
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
Now, if the bool value “val” is true, that would mean the special characters are in the string.
if (val == true)
System.out.println("Special characters are in the string.");
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String []args) {
String str = "test*$demo";
System.out.println("String: "+str);
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
if (val == true)
System.out.println("Special characters are in the string.");
else
System.out.println("Special characters are not in the string.");
}
}
Output
String: test*$demo Special characters are in the string.
The following is another example with a different input.
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String []args) {
String str = "testdemo";
System.out.println("String: "+str);
Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
if (val == true)
System.out.println("Special characters are in the string.");
else
System.out.println("Special characters are not in the string.");
}
}
Output
String: testdemo Special characters are not in the string...
Advertisements