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

您可以使用以下代碼從字符串中檢測特殊字符。

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

如果您想在密碼中包含至少 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 ]*則其中沒有特殊字符。

你究竟把什么叫做“特殊字符”? 如果你的意思是“任何不是字母數字的東西”,你可以使用 org.apache.commons.lang.StringUtils 類(方法 IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable)。

如果不是那么簡單,您可以使用正則表達式來定義您接受的確切字符列表並將字符串與其匹配。

一切都取決於您所說的“特殊”是什么意思。 在正則表達式中,您可以指定

  • \\W 表示非字母數字
  • \\p{Punct} 表示標點符號

我懷疑后者就是你的意思。 但如果不使用 [] 列表來准確指定您想要的內容。

看看java.lang.Character類。 它有一些測試方法,您可能會找到適合您需求的方法。

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

這已在 android 7.0 到 android 10.0 中進行了測試,並且可以正常工作

使用此代碼檢查字符串是否包含特殊字符和數字:

  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
  }

這對我有用:

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

首先,您必須徹底確定要檢查的特殊字符。

然后你可以寫一個正則表達式並使用

public boolean matches(String regex)

//不使用正則表達式........

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

//這是我發布的代碼的更新版本 /* 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.");

訪問字符串中的每個字符,查看該字符是否在特殊字符黑名單中; 這是 O(n*m)。

偽代碼是:

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

通過對黑名單進行排序,可以稍微提高復雜性,以便您可以提前退出每個檢查。 但是,字符串查找函數可能是本機代碼,因此這種優化(在 Java 字節碼中)可能會更慢。

在 String str2[]=name.split("") 行中; 在數組中給出一個額外的字符...讓我通過示例來解釋“Aditya”.split("") 將返回 [, A, d,i,t,y,a] 你的數組中會有一個額外的字符.. .
"Aditya".split("") 無法按 saroj routray 的預期工作,您將在 String => [, A, d,i,t,y,a] 中得到一個額外的字符。

我已經修改了它,請參閱下面的代碼它按預期工作

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

將字符串轉換為所有字母為小寫的 char 數組:

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

然后你可以使用Character.isLetterOrDigit(c[index])找出哪個索引有特殊字符。

使用 java.util.regex.Pattern 類的靜態方法matches(regex, String obj)
正則表達式:小寫和大寫字符以及 0-9 之間的數字
String obj :要檢查是否包含特殊字符的字符串對象。

如果只包含字符和數字,則返回布爾值 true,否則返回布爾值 false

例子。

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