我正在为Uni编写一个程序,它需要一些基本的验证。
我有一个文本框,允许用户输入他们的年龄。我已经成功地编写了一个Regex表达式,该表达式检查输入到文本框中的值是否只包含数值,并且长度为两个字符:
Regex agePattern = new Regex(@"^[0-9]{1,2}\z$"); // Age entered must be numeric characters only (0-9) and may only be two charaters long
if (agePattern.IsMatch(ageBox.Text) == false)
{
MessageBox.Show("Customer's age is not valid. Age must be in numeric format & can only be two characters long"); // If Regex pattern & entered string DO NOT match - user get's this message
return;
}
else
{
// do something
}我的问题是,我是否可以扩展我的正则表达式,将年龄值限制在1到99之间?
我以前没有写过任何正则表达式,我正在努力。
谢谢!
发布于 2016-12-05 05:46:20
解析一个整数怎么样?
bool IsValidAge(string ageString) {
int age;
return int.TryParse(ageString, out age) && age >= 1 && age <= 99;
}发布于 2016-12-05 06:03:49
试试这个正则表达式:
^[1-9]?[0-9]?\z或者跳过正则表达式,将文本解析为int,然后编写一个函数来确定输入在1到99之间。
发布于 2018-03-28 20:57:49
尝试这个正则表达式:
^1-90-9?\z
这匹配空输入(因为两个数字都是可选的)和0。?越少越好:
^[1-9][0-9]?$尝试使用A Better .NET Regular Expression Tester (大多数其他在线测试人员不允许指定空源)。
https://stackoverflow.com/questions/40964023
复制相似问题