Check if a String contains a special character
Asked Answered
P

19

98

How do you check if a String contains a special character like:

[,],{,},{,),*,|,:,>,
Pursue answered 25/11, 2009 at 8:15 Comment(2)
What's it for? I have a nasty feeling this is some kind of field sanitiser to, say, prevent SQL injection attacks on a website. Oh no! This would not be the right way to go about that...Insure
you need to use regular expression.Betsey
T
148
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();

if (b)
   System.out.println("There is a special character in my string");
Thorite answered 25/11, 2009 at 8:25 Comment(3)
you need to import the correct Matcher and Pattern. import java.util.regex.Matcher; import java.util.regex.Pattern; This code is great for telling of the string passed in contains only a-z and 0-9, it won't give you a location of the 'bad' character or what it is, but then the question didn't ask for that. I feel regex is great skill for a programmer to master, I'm still trying.Hifalutin
if you want to show the the bad character you can use m.group() or m.group(index)Superbomb
This will allow you Alpha numeric validation. If you update Reg Ex little bit Like => [^a-z] than it will validate alpha characters only.Collaborationist
R
29

If you want to have LETTERS, SPECIAL CHARACTERS and NUMBERS in your password with at least 8 digit, then use this code, it is working perfectly

public static boolean Password_Validation(String password) 
{

    if(password.length()>=8)
    {
        Pattern letter = Pattern.compile("[a-zA-z]");
        Pattern digit = Pattern.compile("[0-9]");
        Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
        //Pattern eight = Pattern.compile (".{8}");


           Matcher hasLetter = letter.matcher(password);
           Matcher hasDigit = digit.matcher(password);
           Matcher hasSpecial = special.matcher(password);

           return hasLetter.find() && hasDigit.find() && hasSpecial.find();

    }
    else
        return false;

}
Repand answered 17/1, 2017 at 12:49 Comment(2)
Thanks for sharing, this is what I needed!Redundancy
"Perfectly" for those that think that ASCII is all the characters there are.Colous
M
28

You can use the following code to detect special character from string.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DetectSpecial{ 
public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         System.out.println("Incorrect format of string");
         return 0;
     }
     Pattern p = Pattern.compile("[^A-Za-z0-9]");
     Matcher m = p.matcher(s);
    // boolean b = m.matches();
     boolean b = m.find();
     if (b)
        System.out.println("There is a special character in my string ");
     else
         System.out.println("There is no special char.");
     return 0;
 }
}
Maxentia answered 26/6, 2014 at 8:17 Comment(1)
If compared with " abc" then gives true, but if compared with " " then giving false.Dilute
A
15

If it matches regex [a-zA-Z0-9 ]* then there is not special characters in it.

Airla answered 16/6, 2011 at 1:45 Comment(2)
This is not reliable! It only checks for a-zA-Z0-9. Try checking this against 123%#@ABC input. It returns true.Robomb
@RSun That would return falseTierratiersten
E
10

What do you exactly call "special character"? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).

If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.

Extravascular answered 25/11, 2009 at 8:18 Comment(0)
F
8

This is tested in android 7.0 up to android 10.0 and it works

Use this code to check if string contains special character and numbers:

  name = firstname.getText().toString(); //name is the variable that holds the string value

  Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
  Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
  Matcher matcher = special.matcher(name);
  Matcher matcherNumber = number.matcher(name);
  
  boolean constainsSymbols = matcher.find();
  boolean containsNumber = matcherNumber.find();

  if(constainsSymbols){
   //string contains special symbol/character
  }
  else if(containsNumber){
   //string contains numbers
  }
  else{
   //string doesn't contain special characters or numbers
  }
Filberto answered 4/11, 2019 at 5:23 Comment(0)
R
7

All depends on exactly what you mean by "special". In a regex you can specify

  • \W to mean non-alpahnumeric
  • \p{Punct} to mean punctuation characters

I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.

Roncesvalles answered 25/11, 2009 at 8:20 Comment(0)
L
7

Have a look at the java.lang.Character class. It has some test methods and you may find one that fits your needs.

Examples: Character.isSpaceChar(c) or !Character.isJavaLetter(c)

Legume answered 25/11, 2009 at 8:22 Comment(0)
V
4

//without using regular expression........

    String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}~0123456789";
    String name="3_ saroj@";
    String str2[]=name.split("");

    for (int i=0;i<str2.length;i++)
    {
    if (specialCharacters.contains(str2[i]))
    {
        System.out.println("true");
        //break;
    }
    else
        System.out.println("false");
    }
Voroshilovsk answered 22/2, 2017 at 19:22 Comment(0)
G
4

This worked for me:

String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
 System.out.println("clear");
} else {
 System.out.println("buzz");
}
Gladysglagolitic answered 12/9, 2017 at 19:5 Comment(0)
T
3

First you have to exhaustively identify the special characters that you want to check.

Then you can write a regular expression and use

public boolean matches(String regex)
Trinitrocresol answered 25/11, 2009 at 8:25 Comment(1)
It's much safer to make a list of acceptable characters and check against that.Effervesce
J
2
Pattern p = Pattern.compile("[\\p{Alpha}]*[\\p{Punct}][\\p{Alpha}]*");
        Matcher m = p.matcher("Afsff%esfsf098");
        boolean b = m.matches();

        if (b == true)
           System.out.println("There is a sp. character in my string");
        else
            System.out.println("There is no sp. char.");
Jdavie answered 16/6, 2011 at 1:35 Comment(0)
V
2

//this is updated version of code that i posted /* The isValidName Method will check whether the name passed as argument should not contain- 1.null value or space 2.any special character 3.Digits (0-9) Explanation--- Here str2 is String array variable which stores the the splited string of name that is passed as argument The count variable will count the number of special character occurs The method will return true if it satisfy all the condition */

public boolean isValidName(String name)
{
    String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}~0123456789";
    String str2[]=name.split("");
    int count=0;
    for (int i=0;i<str2.length;i++)
    {
        if (specialCharacters.contains(str2[i]))
        {
            count++;
        }
    }       

    if (name!=null && count==0 )
    {
        return true;
    }
    else
    {
        return false;
    }
}
Voroshilovsk answered 23/2, 2017 at 6:36 Comment(0)
I
1

Visit each character in the string to see if that character is in a blacklist of special characters; this is O(n*m).

The pseudo-code is:

for each char in string:
  if char in blacklist:
    ...

The complexity can be slightly improved by sorting the blacklist so that you can early-exit each check. However, the string find function is probably native code, so this optimisation - which would be in Java byte-code - could well be slower.

Insure answered 25/11, 2009 at 8:24 Comment(0)
C
1

in the line String str2[]=name.split(""); give an extra character in Array... Let me explain by example "Aditya".split("") would return [, A, d,i,t,y,a] You will have a extra character in your Array...
The "Aditya".split("") does not work as expected by saroj routray you will get an extra character in String => [, A, d,i,t,y,a].

I have modified it,see below code it work as expected

 public static boolean isValidName(String inputString) {

    String specialCharacters = " !#$%&'()*+,-./:;<=>?@[]^_`{|}~0123456789";
    String[] strlCharactersArray = new String[inputString.length()];
    for (int i = 0; i < inputString.length(); i++) {
         strlCharactersArray[i] = Character
            .toString(inputString.charAt(i));
    }
    //now  strlCharactersArray[i]=[A, d, i, t, y, a]
    int count = 0;
    for (int i = 0; i <  strlCharactersArray.length; i++) {
        if (specialCharacters.contains( strlCharactersArray[i])) {
            count++;
        }

    }

    if (inputString != null && count == 0) {
        return true;
    } else {
        return false;
    }
}
Caretaker answered 25/4, 2017 at 10:46 Comment(0)
S
0

Convert the string into char array with all the letters in lower case:

char c[] = str.toLowerCase().toCharArray();

Then you can use Character.isLetterOrDigit(c[index]) to find out which index has special characters.

Scalariform answered 13/10, 2018 at 21:54 Comment(0)
M
0

There are a few approaches you can take to determine if a string contains a set of specified characters.

You can use a regular expression pattern, specifically a character-class.

"example*".matches(".*?[" + Pattern.quote("[]{}{)*|:>") + "].*");

Or, you can create a for-loop, which returns true if it finds a match.

boolean contains(String string, char... characters) {
    for (char characterA : string.toCharArray()) {
        for (char characterB : characters) {
            if (characterA == characterB)
                return true;
        }
    }
    return false;
}
Margarine answered 22/5, 2023 at 3:48 Comment(0)
V
0

Using .replaceAll() and comparing if the resulting string is the same as the original could be a possible method as well.

For example:

specialCharRegex = "[,=':;><?/~`_.!@#^&*]|\\[|\\]";

if(str.equals(str.replaceAll(specialCharRegex, "")){
    System.out.println(str + " does not contain special characters")
}
else{
    System.out.println(str + " contains special characters"
}
Vezza answered 14/7, 2023 at 2:11 Comment(0)
E
-1

Use java.util.regex.Pattern class's static method matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9
String obj : String object you want to check either it contain special character or not.

It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false

Example.

String isin = "12GBIU34RT12";<br>
if(Pattern.matches("[a-zA-Z0-9]+", isin)<br>{<br>
   &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Valid isin");<br>
}else{<br>
   &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Invalid isin");<br>
}
Endres answered 17/1, 2019 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.