Check for special characters in a string using regex in java

29,893

Solution 1

You can use Pattern matcher for check special character and you can check below example:

Pattern regex = Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");

if (regex.matcher(your_string).find()) {
    Log.d("TTT, "SPECIAL CHARS FOUND");
    return;
} 

Hope this helps you...if you need any help you can ask

Solution 2

An easy way is to check if a string has any non-alphanumeric characters.

TRY THIS,

StringChecker.java

public class StringChecker {

   public static void main(String[] args) {

      String str = "abc$def^ghi#jkl";

      Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher(str);

      System.out.println(str);
      int count = 0;
      while (m.find()) {
         count = count+1;
         System.out.println("position "  + m.start() + ": " + str.charAt(m.start()));
      }
      System.out.println("There are " + count + " special characters");
   }
}

And you get the result look like below:

$ java SpecialChars
abc$def^ghi#jkl
position 3: $
position 7: ^
position 11: #
There are 3 special characters

You can pass your own patterns as param in compile methods as per your needs to checking special characters:

Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");

Solution 3

You can use the following RegExp:

private boolean emptySpacecheck(String msg){
    return msg.matches(".*\\s+.*");
}
  • \s matches with these characters: [ \t\n\x0B\f\r]

Try it online: https://regex101.com/r/GztOoI/1

Solution 4

...when i enter special chars it's considering them as space.

Which means you only want to check whether String contains space or not.

You don't need regular expression to check for space. You can simply call String#contains method.

private boolean emptySpacecheck(String msg){
    return msg != null && msg.contains(" ");
}
Share:
29,893
Stackover67
Author by

Stackover67

Updated on July 24, 2022

Comments

  • Stackover67
    Stackover67 almost 2 years

    How to check for special chars in a string? I am checking for just empty spaces using regex but when i enter special chars it's considering them as space. Below is my code

      private boolean emptySpacecheck(String msg){
    
        return msg.matches(".*\\w.*");
    }
    

    How to check for special chars?

    • frogatto
      frogatto over 6 years
      White space is \s not \w.