hBifTs

山自高兮水自深!當塵霧消散,唯事實留傳.荣辱不惊, 看庭前花开花落; 去留随意, 望天上云展云舒.

导航

利用正则表达式检测用户的输入 :)

Posted on 2004-06-14 22:25  hbiftsaa  阅读(2804)  评论(21编辑  收藏  举报
siko的帖子:c#初学者,望指教 中,他提到了一个问题,
  string s = Console.ReadLine();
  int a = int.Parse(s);

对于上述代码,怎么很方便的检测输入的为Int型,而且性能不能影响很大.

我在评论中给出的一个方案就是,使用Try catch

int x;
while(true){

try{
x = Int32.Parse(..);
break;
}
catch(Exception ex){
Console.WriteLine(...);
}
}

但是dudu发现,这样做很影响性能.而性能的影响都是由于转换不成功,Throw 的Exception引起的.(由sumtec解释)
而且sumtec也提出了一种解决方案:
s = s.Trim();
switch (s[0])
{
  case '1':
   ...
   break;
  case '2':
   ...
   break;
  case '3':
   ...
   break;
  default:
   ...
   break;
}

或者:
s = s.Trim();
byte b = Encoding.Ascii.GetByte(s[0]);
switch(b - 0x30)
{
  case 1:
    ...
  ....
}


上述代码应该是可以完成了siko的问题了的.
但是我始终觉得这样做太,,,,厄,怎么说呢,麻烦?还是别的..
反正就是和本来的意图不相同了吧..

其实此问题的主要原因在于,确定用户输入的字符串为0-9的数字,不是字母.
这时,我们就可以通过正则表达式来对输入进行验证:)
代码如下:

   string regx = @"^\d+$";
   string temp;
   Regex reg = new Regex(regx );
   while(true){
    temp = Console.ReadLine();
    Console.WriteLine("input : " + temp);
    if( reg.IsMatch(temp) ){
     break;
    }
   }
   Console.WriteLine("hehe");
   int x = Int32.Parse(temp);
   Console.WriteLine(x);

这样,就可以很方便的检测输入的是不是数字了.呵呵...