Nice programing

LINQ를 사용하여 문자열에 숫자가 하나 이상 있는지 확인

nicepro 2020. 11. 6. 20:04
반응형

LINQ를 사용하여 문자열에 숫자가 하나 이상 있는지 확인


문자열에 숫자 문자가 포함 된 경우 true를 반환하는 가장 쉽고 짧은 LINQ 쿼리가 무엇인지 알고 싶습니다.


"abc3def".Any(c => char.IsDigit(c));

업데이트 : @Cipher가 지적했듯이 실제로 더 짧게 만들 수 있습니다.

"abc3def".Any(char.IsDigit);

이 시도

public static bool HasNumber(this string input) {
  return input.Where(x => Char.IsDigit(x)).Any();
}

용법

string x = GetTheString();
if ( x.HasNumber() ) {
  ...
}

또는 Regex를 사용하여 가능합니다.

string input = "123 find if this has a number";
bool containsNum = Regex.IsMatch(input, @"\d");
if (containsNum)
{
 //Do Something
}

이건 어때:

bool test = System.Text.RegularExpressions.Regex.IsMatch(test, @"\d");

string number = fn_txt.Text;   //textbox
        Regex regex2 = new Regex(@"\d");   //check  number 
        Match match2 = regex2.Match(number);
        if (match2.Success)    // if found number 
        {  **// do what you want here** 
            fn_warm.Visible = true;    // visible warm lable
            fn_warm.Text = "write your text here ";   /
        }

참고 URL : https://stackoverflow.com/questions/1540620/check-if-a-string-has-at-least-one-number-in-it-using-linq

반응형