Console.ReadLine()是无法限制控制台输入的,当然可以用regexp匹配正则,失败后从新Console.ReadLine()
另一种方法就是每次只获取一个字符
string s = "";
ConsoleKeyInfo k = Console.ReadKey();
while (k.Key != ConsoleKey.Enter)
{
if (k.KeyChar >= '0' && k.KeyChar <= '9')
{
s += k.KeyChar;
Console.Write(k.KeyChar)
}
k = Console.ReadKey();
}
using System.Text.RegularExpressions;
string a = "";
a = Console.ReadLine();
while (!IsNum(a))
{
Console.WriteLine("非数字,请重新输入。");
a = Console.ReadLine();
}
Console.WriteLine("输入的数字是:{0}", a);
private static bool IsNum(string s)
{
return Regex.IsMatch(s, @"^\d+");
}
应该是:
Console.Wrtiteline("请输入数字:");
是这样吗?
用正则表达式
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string a = "";
a = Console.ReadLine();
while (!IsNum(a))
{
Console.WriteLine("非数字,请重新输入。");
a = Console.ReadLine();
Console.WriteLine("刚才输入的内容为:" + a);
Console.ReadLine();
}
}
private static bool IsNum(string s)
{
return Regex.IsMatch(s, @"^\d+");
}
}
}
即可