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

 Live Demo

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

 Live Demo

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...

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements