Programing

문자열에 특수 문자가 포함되어 있는지 확인

lottogame 2020. 11. 13. 07:44
반응형

문자열에 특수 문자가 포함되어 있는지 확인


문자열에 다음과 같은 특수 문자가 포함되어 있는지 어떻게 확인합니까?

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

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

정규식과 일치하면 [a-zA-Z0-9 ]*특수 문자가 없습니다.


비밀번호에 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;

}

정확히 "특수 문자"라고 부르는 것은 무엇입니까? "영숫자가 아닌 모든 것"과 같은 것을 의미한다면 org.apache.commons.lang.StringUtils 클래스 (IsAlpha / IsNumeric / IsWhitespace / IsAsciiPrintable 메소드)를 사용할 수 있습니다.

그렇게 사소하지 않은 경우 수락하고 문자열을 일치시키는 정확한 문자 목록을 정의하는 정규식을 사용할 수 있습니다.


모두 "특별한"이 무엇을 의미하는지에 따라 다릅니다. 정규식에서 다음을 지정할 수 있습니다.

  • \ W는 알파벳이 아닌 숫자를 의미합니다.
  • 구두점 문자를 의미하는 \ p {Punct}

나는 후자가 당신이 의미하는 바라고 생각합니다. 그러나 그렇지 않은 경우 [] 목록을 사용하여 원하는 것을 정확하게 지정하십시오.


java.lang.Character수업을 살펴보십시오 . 몇 가지 테스트 방법이 있으며 필요에 맞는 방법을 찾을 수 있습니다.

예 : Character.isSpaceChar(c)또는!Character.isJavaLetter(c)


먼저 확인하려는 특수 문자를 철저히 식별해야합니다.

그런 다음 정규 표현식을 작성하고

public boolean matches(String regex)

문자열의 각 문자를 방문하여 해당 문자가 특수 문자의 블랙리스트에 있는지 확인하십시오. 이것은 O (n * m)입니다.

의사 코드는 다음과 같습니다.

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

블랙리스트를 정렬하여 복잡성을 약간 개선 할 수 있으므로 각 검사를 일찍 종료 할 수 있습니다. 그러나 문자열 찾기 기능은 아마도 네이티브 코드 일 것이므로이 최적화 (Java 바이트 코드에 있음)는 더 느릴 수 있습니다.


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

// 정규식을 사용하지 않고 ........

    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는 인자로 전달 된 이름의 분할 된 문자열을 저장하는 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;
    }
}

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

This worked for me:

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

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.


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

참고URL : https://stackoverflow.com/questions/1795402/check-if-a-string-contains-a-special-character

반응형