문자열에 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_]+$");
}
문자열의 문자를 루프하고 Char Method IsLetter를 사용하여 확인할 수 있지만 String method IndexOfAny를 사용하여 문자열에 포함되지 않아야 하는 다른 문자를 검색할 수도 있습니다.
문자열 문자를 반복하고, 'Char'의 기능인 'IsLetter'와 'IsDigit'을 사용합니다.
보다 구체적인 내용이 필요한 경우 Regex 클래스를 사용합니다.
패턴 매칭을 사용하는 솔루션을 아직 보지 못했습니다.
public static bool ContainsOnlyLetters(this string input)
{
bool isValid = true;
for (int i = 0; isValid && i < input.Length; i++)
{
isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z';
}
return isValid;
}
또는 읽기 쉬운 코드를 정말 싫어한다면:
public static bool ContainsOnlyLetters(this string input)
{
bool isValid = true;
for (int i = 0; i < input.Length && (isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z'); i++);
return isValid;
}
저는 알파벳과 공백만 받을 수 있도록 수표를 추가했습니다.두 번째 if 문 뒤에 for loop을 반복하여 문자열의 유효성을 다시 확인할 수 있습니다.
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;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
최근 이 페이지의 도움을 받아 문자열로 글자를 확인하는 기능의 성능 개선을 하였습니다.
제가 알아본 결과, regex를 사용한 솔루션은 Char를 사용한 솔루션보다 30배나 느립니다.LetterOrDigit 체크입니다.
우리는 그러한 문자나 숫자가 포함되는지 확신할 수 없었고 라틴 문자만 필요했기 때문에 Char의 디컴파일 버전을 기반으로 우리의 기능을 구현했습니다.LetterOrDigit 함수입니다.
다음은 우리의 해결책입니다.
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;
}
}
사용법은 다음과 같습니다.
if( logicalId.All(c => CheckAllowedChars(c)))
{ // Do your stuff here.. }
문자가 문자인지, 숫자인지, 공백인지 확인할 방법을 찾으십시오. 그렇지 않으면 밑줄을 붙입니다(필요에 따라 자유롭게 수정하십시오).
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;
}
문자열의 각 문자를 스캔합니다.
SPACE' 이외에 "많은" 문자를 포함하려면 1 IF STATION 뒤에 SWITCH STATION을 추가할 수 있습니다.
string myInput = string.Empty;
bool check = false;
// Loops the input module
while (check is false)
{
Console.WriteLine("Enter Letters Only");
myInput = Console.ReadLine();
// Loops the SCANNING PROCCESS of each character of the string
for (int i = 0; i < myInput.Length; i++)
{
// Prints current scanning proccess 1 by 1(character by character) inside the string
Console.WriteLine("Checking Character \"{0}\" ",myInput[i]);
// Letters only
if (Char.IsLetter(myInput[i]))
{
check = true;
}
// Includes "SPACE" character
else if (myInput[i] == ' ')
{
check = true;
}
else
{
check = false;
Console.WriteLine("wrong input. \"{0}\" is not a string", myInput[e]);
Console.WriteLine("pls try again");
// Exits from loop of scanning proccess due to unwanted input
break;
}
}
// Ends SCANNING of 1 CHARACTER inside the string
}
Console.WriteLine("Input Approved: \"{0}\"", myInput);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
출력: FALSE 입력 포함
에이전트 47
문자 "A" 하기 "A" 하기를 하는 중
"g" 하기 "g"
"e" 하기 확인하기
"n" "n"
"t" "t" 확인하기
확인 " " "
"4" "4"
"한 입력 , "4" 이 는 이 이 아닙니다.
다시 시도해 주세요.
문자만
출력: FALSE 입력 없음
세븐 作
문자 "A" 하기 "A" 하기를 하는 중
"g" 하기 "g"
"e" 하기 확인하기
"n" "n"
"t" "t" 확인하기
확인 " " "
문자 "F" 하기
"o" "o"
"r" "r" 확인하기
"t" "t" 확인하기
"y" 하기 "y"
확인 " " "
"S" 하기 확인하기
"e" 하기 확인하기
"v"
"e" 하기 확인하기
"n" "n"
" 포티 세븐" : "fault 47"
종료
또는 LETTER 카테고리의 "일부" 문자와 DIGIT 카테고리의 "일부" 문자만 포함하려는 경우에만 SWITCH STATEMENT.
switch (myInput[e])
{
case 'a':
case 'b':
case 'c':
case 'd':
case '1':
case '2':
case '3':
case '!':
case '@':
case '#':
check = true;
break;
default:
check = false;
Console.WriteLine("Oops, \"{0}\" is not a string", myInput[i]);
Console.WriteLine("pls try again\n");
break;
}
if (check == false) break ;
언급URL : https://stackoverflow.com/questions/1181419/verifying-that-a-string-contains-only-letters-in-c-sharp
'programing' 카테고리의 다른 글
| Ember의 모델을 주기적으로 업데이트하는 방법(setInterval 등)? (0) | 2023.09.14 |
|---|---|
| mariadb에서 다른 두 열의 연결인 열을 만들려면 어떻게 해야 합니까? (0) | 2023.09.14 |
| 안드로이드에서 푸시 알림 기술은 어떻게 작동합니까? (0) | 2023.09.14 |
| overflow-x:숨김으로 모바일 브라우저에서 콘텐츠가 넘쳐나는 것을 방지하지 못합니다. (0) | 2023.09.14 |
| ASP를 사용하여 브라우저에 PDF를 반환합니다.NET 코어 (0) | 2023.09.14 |