简体   繁体   English

检查字符串是否包含特殊字符

[英]Check if a String contains a special character

如何检查字符串是否包含特殊字符,例如:

[,],{,},{,),*,|,:,>,
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");

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

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;

}

如果它匹配正则表达式[a-zA-Z0-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.如果不是那么简单,您可以使用正则表达式来定义您接受的确切字符列表并将字符串与其匹配。

All depends on exactly what you mean by "special".一切都取决于您所说的“特殊”是什么意思。 In a regex you can specify在正则表达式中,您可以指定

  • \\W to mean non-alpahnumeric \\W 表示非字母数字
  • \\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.但如果不使用 [] 列表来准确指定您想要的内容。

Have a look at the java.lang.Character class.看看java.lang.Character类。 It has some test methods and you may find one that fits your needs.它有一些测试方法,您可能会找到适合您需求的方法。

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

This is tested in android 7.0 up to android 10.0 and it works这已在 android 7.0 到 android 10.0 中进行了测试,并且可以正常工作

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 == true){
   //string contains special symbol/character
  }
  else if(containsNumber == true){
   //string contains numbers
  }
  else{
   //string doesn't contain special characters or numbers
  }

This worked for me:这对我有用:

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

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)

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

//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. 任何特殊字符 3.Digits (0-9) 说明-- - 这里 str2 是字符串数组变量,它存储作为参数传递的名称的拆分字符串 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;
    }
}
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.");

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 字节码中)可能会更慢。

in the line String str2[]=name.split("");在 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...在数组中给出一个额外的字符...让我通过示例来解释“Aditya”.split("") 将返回 [, A, d,i,t,y,a] 你的数组中会有一个额外的字符.. .
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]. "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;
    }
}

Convert the string into char array with all the letters in lower case:将字符串转换为所有字母为小写的 char 数组:

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

Then you can use Character.isLetterOrDigit(c[index]) to find out which index has special characters.然后你可以使用Character.isLetterOrDigit(c[index])找出哪个索引有特殊字符。

Use java.util.regex.Pattern class's static method matches(regex, String obj)使用 java.util.regex.Pattern 类的静态方法matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9正则表达式:小写和大写字符以及 0-9 之间的数字
String obj : String object you want to check either it contain special character or not. String obj :要检查是否包含特殊字符的字符串对象。

It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false如果只包含字符和数字,则返回布尔值 true,否则返回布尔值 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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM