C# 使用 LINQ 检查字符串中是否至少有一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1540620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:37:00  来源:igfitidea点击:

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

c#linq

提问by Jobi Joy

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.

我想知道如果字符串中包含任何数字字符,最简单和最短的 LINQ 查询是返回 true。

采纳答案by Fredrik M?rk

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

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

更新:正如@Cipher 所指出的,它实际上可以做得更短:

"abc3def".Any(char.IsDigit);

回答by JaredPar

Try this

尝试这个

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

Usage

用法

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

回答by Elegiac

or possible using Regex:

或可能使用正则表达式:

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

回答by Aaron

How about this:

这个怎么样:

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

回答by inal

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