May 10, 2020
Estimated Post Reading Time ~

How to check for special characters in String in Java

While working with various String objects, we sometimes end up with a requirement where we need to check if a string contains special characters or not. This can be done simply using the below code snippet.

File: CheckSpecialCharacters.java

package net.codermag.sample;

public class CheckSpecialCharacters {

 public static void main(String[] args) {
  
  String s = "HelloWorld";
  System.out.println("Contains no special Chars: "+s.matches("[a-zA-Z0-9]*"));

  String s1 = "Hell@ W@rld..%$#*@*@!!";
  System.out.println("Contains no special Chars: "+s1.matches("[a-zA-Z0-9]*"));
  
  //Remove all special characters
  System.out.println(s1.replaceAll("[^\\w]", ""));
  
  //Remove all special characters except space
  System.out.println(s1.replaceAll("[^\\w\\s]", ""));
 }
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.