我是C#.net的新手.我想要一个仅采用hh:mm:ss格式的文本框验证.下面是我的代码和它的wroking.它给出的输出为真23:45:45(仅示例),对于-23:45:45也是如此(仅示例).现在我希望验证返回false为-23:45:45(仅示例),因为它是负时间.我的运行代码在负时间内不起作用.
IsTrue = ValidateTime(txtTime.Text);
if (!IsTrue)
{
strErrorMsg += "\nPlease insert valid alpha time in hh:mm:ss formats";
isValidate = false;
}
public bool ValidateTime(string time)
{
try
{
Regex regExp = new Regex(@"(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");
return regExp.IsMatch(time);
}
catch (Exception ex)
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
我根本不会使用正则表达式 - 我只是尝试DateTime使用自定义格式解析结果:
public bool ValidateTime(string time)
{
DateTime ignored;
return DateTime.TryParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out ignored);
}
Run Code Online (Sandbox Code Playgroud)
(如果你真的想坚持使用正则表达式,请遵循Mels的答案.我将摆脱无意义的try/catch块,并且可能只构造一次正则表达式并重用它.)
将您的正则表达式用^开头和$括起来。这些标记字符串的开头和结尾,并且在存在其他任何字符时使匹配无效。