JAVA:检查字符串是否有特殊字符

时间:2022-09-01 21:39:16

How do you check a string if there is a special character like:

如果有特殊字符,如何检查字符串:

           [,],{,},{,),*,|,:,>,

14 个解决方案

#1


102  

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");

#2


15  

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 == true)
        System.out.println("There is a special character in my string ");
     else
         System.out.println("There is no special char.");
     return 0;
 }
}

#3


12  

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

如果它匹配正则表达式[a-zA-Z0-9] *,那么它中没有特殊字符。

#4


9  

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).

你究竟称之为“特殊人物”?如果您的意思是“任何不是字母数字的东西”,您可以使用org.apache.commons.lang.StringUtils类(方法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.

如果它不是那么简单,您可以使用正则表达式来定义您接受的确切字符列表并将字符串与其匹配。

#5


7  

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

一切都取决于你所说的“特殊”。在正则表达式中,您可以指定

  • \W to mean non-alpahnumeric
  • \ W表示非alpahnumeric
  • \p{Punct} to mean punctuation characters
  • \ p {Punct}表示标点字符

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

我怀疑后者就是你的意思。但如果不使用[]列表来准确指定您想要的内容。

#6


7  

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

看看java.lang.Character类。它有一些测试方法,你可以找到一个适合你的需求。

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

示例:Character.isSpaceChar(c)或!Character.isJavaLetter(c)

#7


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)

#8


3  

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

如果您想在密码中包含至少8位数字的字母,特殊字符和数字,那么使用此代码,它可以正常工作

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;

}

#9


1  

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

访问字符串中的每个字符以查看该字符是否在特殊字符的黑名单中;这是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.

通过对黑名单进行排序可以略微提高复杂性,以便您可以提前退出每个检查。但是,字符串查找功能可能是本机代码,因此这种优化 - 可能是Java字节代码 - 可能会慢一些。

#10


1  

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.");

#11


1  

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

#12


1  

//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 */

//这是我发布的代码的更新版本/ * isValidName方法将检查作为参数传递的名称是否不应包含 - 1.null值或空格2.any特殊字符3.Digits(0-9)说明 - - 这里str2是String数组变量,它存储作为参数传递的名称的分割字符串count变量将计算发生的特殊字符的数量如果满足所有条件,则该方法将返回true * /

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;
    }
}

#13


0  

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].

在行str2 [] = name.split(“”);在Array中给出一个额外的字符...让我通过例子解释“Aditya”.split(“”)会返回[,A,d,i,t,y,a]你的数组中会有一个额外的字符.. 。“Aditya”.split(“”)无法按照saroj routray的预期工作,你将在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;
    }
}

#14


0  

this worked for me

这对我有用

    String s = "string"; 
    if(Pattern.matches("[a-zA-Z]+", s)) 
    {  
    System.out.println("clear"); 
     }  
     else  
     {  
     System.out.println("buzz"); 
     }  

#1


102  

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");

#2


15  

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 == true)
        System.out.println("There is a special character in my string ");
     else
         System.out.println("There is no special char.");
     return 0;
 }
}

#3


12  

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

如果它匹配正则表达式[a-zA-Z0-9] *,那么它中没有特殊字符。

#4


9  

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).

你究竟称之为“特殊人物”?如果您的意思是“任何不是字母数字的东西”,您可以使用org.apache.commons.lang.StringUtils类(方法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.

如果它不是那么简单,您可以使用正则表达式来定义您接受的确切字符列表并将字符串与其匹配。

#5


7  

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

一切都取决于你所说的“特殊”。在正则表达式中,您可以指定

  • \W to mean non-alpahnumeric
  • \ W表示非alpahnumeric
  • \p{Punct} to mean punctuation characters
  • \ p {Punct}表示标点字符

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

我怀疑后者就是你的意思。但如果不使用[]列表来准确指定您想要的内容。

#6


7  

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

看看java.lang.Character类。它有一些测试方法,你可以找到一个适合你的需求。

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

示例:Character.isSpaceChar(c)或!Character.isJavaLetter(c)

#7


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)

#8


3  

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

如果您想在密码中包含至少8位数字的字母,特殊字符和数字,那么使用此代码,它可以正常工作

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;

}

#9


1  

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

访问字符串中的每个字符以查看该字符是否在特殊字符的黑名单中;这是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.

通过对黑名单进行排序可以略微提高复杂性,以便您可以提前退出每个检查。但是,字符串查找功能可能是本机代码,因此这种优化 - 可能是Java字节代码 - 可能会慢一些。

#10


1  

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.");

#11


1  

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

#12


1  

//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 */

//这是我发布的代码的更新版本/ * isValidName方法将检查作为参数传递的名称是否不应包含 - 1.null值或空格2.any特殊字符3.Digits(0-9)说明 - - 这里str2是String数组变量,它存储作为参数传递的名称的分割字符串count变量将计算发生的特殊字符的数量如果满足所有条件,则该方法将返回true * /

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;
    }
}

#13


0  

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].

在行str2 [] = name.split(“”);在Array中给出一个额外的字符...让我通过例子解释“Aditya”.split(“”)会返回[,A,d,i,t,y,a]你的数组中会有一个额外的字符.. 。“Aditya”.split(“”)无法按照saroj routray的预期工作,你将在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;
    }
}

#14


0  

this worked for me

这对我有用

    String s = "string"; 
    if(Pattern.matches("[a-zA-Z]+", s)) 
    {  
    System.out.println("clear"); 
     }  
     else  
     {  
     System.out.println("buzz"); 
     }