C# 使用LINQ检查字符串中是否至少有一个数字
我想知道,如果字符串中包含任何数字字符,最简单、最短的LINQ查询返回true是什么。试试这个C# 使用LINQ检查字符串中是否至少有一个数字,c#,linq,C#,Linq,我想知道,如果字符串中包含任何数字字符,最简单、最短的LINQ查询返回true是什么。试试这个 public static bool HasNumber(this string input) { return input.Where(x => Char.IsDigit(x)).Any(); } 用法 更新:如前所述,它实际上可以缩短: "abc3def".Any(char.IsDigit); 或可能使用正则表达式: string input = "123 find if this
public static bool HasNumber(this string input) {
return input.Where(x => Char.IsDigit(x)).Any();
}
用法
更新:如前所述,它实际上可以缩短:
"abc3def".Any(char.IsDigit);
或可能使用正则表达式:
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");
或者干脆
input.Any(x=>Char.IsDigit(x))代码>@Mehrdad,是的,我总是忘记那件事overload@saul悬赏是怎么回事?标记的答案是可信的。我不认为这真的回答了这个问题,因为这个问题对简短的查询感兴趣,而且已经有很多比这个更简洁的查询了。虽然我使用的是4.5框架,但我找不到All()和Any()方法。你知道为什么吗?@cihata87确保你已经使用System.Linq添加了代码>位于代码文件的顶部。
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 "; /
}