[英]How to use Regex in c# for the following situation
我有一个文本框,其中,当用户尝试输入单词时,格式应仅以“ PHY”开头,后跟8位数字。
例如,
正确的格式是PHY00000000
在这里,前三个字母“ PHY”是常数,而后8个数字则从00000000到10000000。
如何使用正则表达式条件获取此格式? 不应该支持其他格式。
如果要使用正则表达式表示范围从PHY00000000
到PHY10000000
值,则应使用:
PHY[0-1]\d{7}
但是我不喜欢这样,因为我们正在尝试使用正则表达式解释数字的值。 我将使用它们来拆分此输入并将其解释为具有指定范围的数字(然后您可以轻松更改此有效数字范围):
static bool Valid(string input)
{
const string Pattern = @"PHY(\d{8})";
const int Max = 10000000;
var match = Regex.Match(input, Pattern);
if (match.Success)
{
int value = int.Parse(match.Groups[1].Value);
if (value <= Max)
{
return true;
}
}
return false;
}
因此,您可以从某些配置中选择Pattern
和Max
。
为了满足要求,将使用以下正则表达式:
const string match = "PHY(0\d{7}|1(0){7})";
然后,您可以通过一种简单的方法来验证输入:
bool ValidateInput(string input)
{
var regex = new Regex(match);
return regex.IsMatch(input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.