2012-04-17 48 views
0

我正在学习C#和 我有一个小测试程序,控制台应该接收一个数字作为输入而不是字母字符。查询正则表达式对象检查指定的字符串模式

string inputString; 

     string pattern = "[A-Za-z]*"; 
     Regex re = new Regex(pattern); 

     inputString = Console.ReadLine(); 

     while(re.Match(inputString).Success) 
     { 
      Console.WriteLine("Please stick to numerals"); 
      inputString = Console.ReadLine(); 
     } 
     Console.WriteLine(inputString); 

问题是编译器不区分字母或数字。

任何建议也许 代码似乎是正确的。

回答

2

的问题是,string pattern = "[A-Za-z]*";也将匹配,因为*量词的0字符:如果你愿意/能够使用LINQ extension methods OU甚至可以缩短这个方法。

如果你只是想检查是否有字符串中的信,只是用

string pattern = "[A-Za-z]"; 

但当然,这仅仅是相匹配的ASCII字母。更好的方法是使用Unicode属性

string pattern = @"\p{L}"; 

\p{L}将匹配属性“信”任何Unicode代码点。

注:

我希望大家都知道,这是不检查只有数字,它检查是否有输入一个字母。这当然会接受不是数字而不是字母的字符!

如果你想支票只有数字你应该去@ musefan的答案,或使用正则表达式这样

string inputString; 

string pattern = @"^\p{Nd}+$"; 
Regex re = new Regex(pattern); 

inputString = Console.ReadLine(); 

while (!re.Match(inputString).Success) { 
    Console.WriteLine("Please stick to numerals"); 
    inputString = Console.ReadLine(); 
} 
Console.WriteLine(inputString); 

\p{Nd}\p{Decimal_Digit_Number}:通过九任何脚本数字零,除了表意文字。有关Unicode属性的更多信息,请参阅www.regular-expressions.info/unicode

下一个替代方案是检查是否存在“不是一个数字”输入:你只需要改变的格局,\P{Nd}

string pattern = @"\P{Nd}"; 
... 
while (re.Match(inputString).Success) { 

的是\p{Nd}的否定和匹配,如果输入中有一个非数字。

+0

我可能总体上首选检查所有数字而不是查找字符:'“^ [0-9] + $”'(我的RegEx虽然不是很好,但这可能是错误的) – musefan 2012-04-17 08:00:59

+0

@musefan我更新了我的答案与数字替代检查。 – stema 2012-04-17 08:13:35

4

我不是过度使用正则表达式的粉丝,所以这里是一个另类,你总是可以尝试...

public bool IsNumeric(string input) 
{ 
    foreach(char c in input) 
    { 
     if(!char.IsDigit(c)) 
     { 
      return false; 
     } 
    } 

    return true; 
} 

您可以使用此如下...

while(!IsNumeric(inputString)) 
{ 
    Console.WriteLine("Please stick to numerals"); 
    inputString = Console.ReadLine(); 
} 

.. 。当然,如果你想的正则表达式我相信有人会尽快整理你出去;)


与感谢礼阿贝尔通过下面的评论,Y

public bool IsNumeric(string input) 
{ 
    return input.All(x => char.IsDigit(x)); 
} 
+1

+1虽然我只是简单地使用input.All(c => char.IsDigit(c)) – 2012-04-17 08:03:21

+0

@EliArbel:很好的调用,我没有使用'.All'。我在我的问题中添加了更多信息,以反映您对备选解决方案的评论 – musefan 2012-04-17 08:10:14

+0

+1。现在用lambda表达式看起来比遍历所有字符好得多。 – stema 2012-04-17 08:12:15

相关问题