Check if a string has at least one number in it using LINQ

后端 未结 5 934
既然无缘
既然无缘 2020-12-04 21:07

I would like to know what the easiest and shortest LINQ query is to return true if a string contains any number character in it.

相关标签:
5条回答
  • 2020-12-04 21:14
    "abc3def".Any(c => char.IsDigit(c));
    

    Update: as @Cipher pointed out, it can actually be made even shorter:

    "abc3def".Any(char.IsDigit);
    
    0 讨论(0)
  • 2020-12-04 21:23

    How about this:

    bool test = System.Text.RegularExpressions.Regex.IsMatch(test, @"\d");
    
    0 讨论(0)
  • 2020-12-04 21:23
    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 ";   /
            }
    
    0 讨论(0)
  • 2020-12-04 21:33

    Try this

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

    Usage

    string x = GetTheString();
    if ( x.HasNumber() ) {
      ...
    }
    
    0 讨论(0)
  • 2020-12-04 21:35

    or possible using Regex:

    string input = "123 find if this has a number";
    bool containsNum = Regex.IsMatch(input, @"\d");
    if (containsNum)
    {
     //Do Something
    }
    
    0 讨论(0)
提交回复
热议问题