Saturday, 16 April 2016

How to check for Special Characters in a String in Java

How to check for Special Characters in a String in Java

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]", ""));
 }
}

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.