Check that the String does not contain certain characters in Java

Java 8Object Oriented ProgrammingProgramming

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...
raja
Published on 14-Dec-2018 11:16:37
Advertisements