使用Regex仅验证一个月 [英] Validate only month using Regex
本文介绍了使用Regex仅验证一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
字符串item1 ="06/14/2012";(MM/dd/yyyy)formate
hi all
string item1 = "06/14/2012";(MM/dd/yyyy)formate
//this is validate the year using Regex
if (Regex.IsMatch(date, @".*/\s*2012", RegexOptions.CultureInvariant))
{
//adding year
}
//if i want to validate month how can i do.?
//in item1 is datetime.
//if i validate item1 how can i know this is particular month
//?
在item1中是日期时间.
如果我验证item1,我怎么知道这是特定月份?
在这里,我只想使用Regex验证几个月.
我该如何执行此功能.
让我知道......
in item1 is datetime.
if i validate item1 how can i know this is particular month?
here i want to validate only months using Regex.
how can i do this functionality.
let me know......
推荐答案
为什么不使用DateTime.TryParseExact [
Why not use the DateTime.TryParseExact[^] method to validate the date.
string date = "06/14/2012"; //(MM/dd/yyyy)format
DateTime dateResult;
if (DateTime.TryParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateResult))
{
Console.WriteLine("This is a valid date.");
}
我根本不会使用正则表达式-使用DateTime.tryParseExact验证很多正则表达式要容易得多:
I wouldn''t use a regex at all - it is a whole lot easier to validate the lot with a DateTime.tryParseExact:
string s = "06/14/2012";
DateTime dt;
if (DateTime.TryParseExact(s, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
}
您未在格式字符串中指定的任何内容都会被默认设置.
Anything you don''t specify in the format string will be defaulted.
您可以使用此正则表达式来验证月份:"^(0?[1-9] | 1 [012] )
You can use this regex for validating month: "^(0?[1-9]|1[012])
这篇关于使用Regex仅验证一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文