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

C#Linq

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

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

"abc3def".Any(char.IsDigit);

Solution 2 - C#

Try this

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

Usage

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

Solution 3 - C#

or possible using Regex:

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

Solution 4 - C#

How about this:

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

Solution 5 - C#

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 ";   /
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJobi JoyView Question on Stackoverflow
Solution 1 - C#Fredrik MörkView Answer on Stackoverflow
Solution 2 - C#JaredParView Answer on Stackoverflow
Solution 3 - C#ElegiacView Answer on Stackoverflow
Solution 4 - C#AaronView Answer on Stackoverflow
Solution 5 - C#inalView Answer on Stackoverflow