2009-10-08 85 views

回答

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

更新:作为@Cipher指出,它实际上可以进行更短:

"abc3def".Any(char.IsDigit); 
+0

虽然我使用4.5,但是我找不到All()和Any框架。你知道为什么吗? – cihata87 2016-06-09 10:41:48

+4

@ cihata87确保您在代码文件的顶部添加了'使用System.Linq;'。 – 2016-06-09 13:34:54

12

试试这个

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

使用

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

或者只是'input.Any(x => Char.IsDigit(x));' – 2009-10-08 21:33:02

+0

@Mehrdad,是的,我经常忘记那个过载 – JaredPar 2009-10-08 21:35:17

8

或可能使用正则表达式:

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

如何:

bool test = System.Text.RegularExpressions.Regex.IsMatch(test, @"\d"); 
-1
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

我不认为这真的回答了这个问题,因为这个问题对短期查询感兴趣,并且已经有很多比这更简洁的问题了。 – JHobern 2015-10-30 22:00:51

相关问题