developer tip

영숫자 문자 만 허용하도록 문자열의 유효성을 검사하려면 어떻게해야합니까?

optionbox 2020. 8. 2. 18:22
반응형

영숫자 문자 만 허용하도록 문자열의 유효성을 검사하려면 어떻게해야합니까?


영숫자 문자 만 허용하도록 정규식을 사용하여 문자열의 유효성을 검사하려면 어떻게해야합니까?

(나는 공백도 허용하고 싶지 않습니다).


다음 표현식을 사용하십시오.

^[a-zA-Z0-9]*$

즉 :

using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}

.NET 4.0에서는 LINQ를 사용할 수 있습니다 :

if (yourText.All(char.IsLetterOrDigit))
{
    //just letters and digits.
}

yourText.All계약을 이행 할 수 없기 때문에 실행을 중지 false하고 최초 char.IsLetterOrDigit보고서를 반환 합니다 .falseAll

노트! 이 답변은 영숫자 (일반적으로 AZ, az 및 0-9)를 엄격하게 확인하지는 않습니다. 이 답변은와 같은 로컬 문자를 허용 åäö합니다.

2018-01-29 업데이트

위의 구문은 올바른 유형의 단일 인수 (이 경우 char) 가있는 단일 메소드를 사용하는 경우에만 작동합니다 .

여러 조건을 사용하려면 다음과 같이 작성해야합니다.

if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x)))
{
}

정규식이 아닌 확장 기능으로 쉽게 할 수 있습니다 ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

댓글 당 :) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}

정규식 기반 솔루션이 아마도 내가 갈 길이라고 생각하지만 이것을 유형으로 캡슐화하려는 유혹을받을 것입니다.

public class AlphaNumericString
{
    public AlphaNumericString(string s)
    {
        Regex r = new Regex("^[a-zA-Z0-9]*$");
        if (r.IsMatch(s))
        {
            value = s;                
        }
        else
        {
            throw new ArgumentException("Only alphanumeric characters may be used");
        }
    }

    private string value;
    static public implicit operator string(AlphaNumericString s)
    {
        return s.value;
    }
}

이제 유효성 검사 된 문자열이 필요할 때 메서드 서명에 AlphaNumericString이 필요하고, 문자열을 가져 오면 유효하다는 것을 알 수 있습니다 (널 제외). 누군가 검증되지 않은 문자열을 전달하려고 시도하면 컴파일러 오류가 발생합니다.

관심이 있다면 더 평등을 얻고 모든 항등 연산자를 구현하거나 일반 문자열에서 AlphaNumericString으로 명시 적으로 캐스트 할 수 있습니다.


AZ, az, 0-9를 확인해야했습니다. 정규 표현식없이 (OP가 정규 표현식을 요구하더라도).

Blending various answers and comments here, and discussion from https://stackoverflow.com/a/9975693/292060, this tests for letter or digit, avoiding other language letters, and avoiding other numbers such as fraction characters.

if (!String.IsNullOrEmpty(testString)
    && testString.All(c => Char.IsLetterOrDigit(c) && (c < 128)))
{
    // Alphanumeric.
}

^\w+$ will allow a-zA-Z0-9_

Use ^[a-zA-Z0-9]+$ to disallow underscore.

Note that both of these require the string not to be empty. Using * instead of + allows empty strings.


In order to check if the string is both a combination of letters and digits, you can re-write @jgauffin answer as follows using .NET 4.0 and LINQ:

if(!string.IsNullOrWhiteSpace(yourText) && 
yourText.Any(char.IsLetter) && yourText.Any(char.IsDigit))
{
   // do something here
}

Based on cletus's answer you may create new extension.

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

I advise to not depend on ready made and built in code in .NET framework , try to bring up new solution ..this is what i do..

public  bool isAlphaNumeric(string N)
{
    bool YesNumeric = false;
    bool YesAlpha = false;
    bool BothStatus = false;


    for (int i = 0; i < N.Length; i++)
    {
        if (char.IsLetter(N[i]) )
            YesAlpha=true;

        if (char.IsNumber(N[i]))
            YesNumeric = true;
    }

    if (YesAlpha==true && YesNumeric==true)
    {
        BothStatus = true;
    }
    else
    {
        BothStatus = false;
    }
    return BothStatus;
}

참고URL : https://stackoverflow.com/questions/1046740/how-can-i-validate-a-string-to-only-allow-alphanumeric-characters-in-it

반응형