IT story

문자열에 C #의 문자 만 포함되어 있는지 확인

hot-time 2020. 5. 23. 09:02
반응형

문자열에 C #의 문자 만 포함되어 있는지 확인


입력 문자열이 있고 다음이 포함되어 있는지 확인하고 싶습니다.

  • 글자 만
  • 문자와 숫자 만
  • 문자, 숫자 또는 밑줄 만

명확히하기 위해 코드에 3 가지 사례가 있으며 각각 다른 검증을 요구합니다. C #에서 이것을 달성하는 가장 간단한 방법은 무엇입니까?


글자 만 :

Regex.IsMatch(input, @"^[a-zA-Z]+$");

문자와 숫자 만 :

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

문자, 숫자 및 밑줄 만 :

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");

bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

문자 만 :

Regex.IsMatch(theString, @"^[\p{L}]+$");

문자와 숫자 :

Regex.IsMatch(theString, @"^[\p{L}\p{N}]+$");

문자, 숫자 및 밑줄 :

Regex.IsMatch(theString, @"^[\w]+$");

이 패턴은 국제 문자와도 일치합니다 ( a-z구문 사용과 반대 ).


Regex를 사용하지 않고 .NET 2.0 프레임 워크 (일명 LINQ)를 사용하는 사람들을 위해 :

편지 만 :

public static bool IsAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsLetter(c))
            return false;
    }
    return true;
}

숫자 만 :

    public static bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

숫자 또는 문자 만 :

    public static bool IsAllLettersOrDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c))
                return false;
        }
        return true;
    }

숫자 나 문자 또는 밑줄 만 :

    public static bool IsAllLettersOrDigitsOrUnderscores(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }

정규 표현식을 사용하는 것이 좋습니다.

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.


Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.


If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again

       bool check = false;

       Console.WriteLine("Please Enter the Name");
       name=Console.ReadLine();

       for (int i = 0; i < name.Length; i++)
       {
           if (name[i]>='a' && name[i]<='z' || name[i]==' ')
           {
               check = true;
           }
           else
           {
               check = false;
           }

       }

       if (check==false)
       {
           Console.WriteLine("Enter Valid Value");
           name = Console.ReadLine();
       }

Recently, I made performance improvements for a function that checks letters in a string with the help of this page.

I figured out that the Solutions with regex are 30 times slower than the ones with the Char.IsLetterOrDigit check.

We were not sure that those Letters or Digits include and we were in need of only Latin characters so implemented our function based on the decompiled version of Char.IsLetterOrDigit function.

Here is our solution:

internal static bool CheckAllowedChars(char uc)
    {
        switch (uc)
        {
            case '-':
            case '.':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return true;
            default:
                return false;
        }
    }

And the usage is like this:

 if( logicalId.All(c => CheckAllowedChars(c)))
 { // Do your stuff here.. }

Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)

public String CleanStringToLettersNumbers(String data)
{
    var result = String.Empty;

    foreach (var item in data)
    {
        var c = '_';

        if ((int)item >= 97 && (int)item <= 122 ||
            (int)item >= 65 && (int)item <= 90 ||
            (int)item >= 48 && (int)item <= 57 ||
            (int)item == 32)
        {
            c = item;
        }

        result = result + c;
    }

    return result;
}

참고URL : https://stackoverflow.com/questions/1181419/verifying-that-a-string-contains-only-letters-in-c-sharp

반응형