如何验证YYYY-MM-DD格式的字符串(C#)

如何验证YYYY-MM-DD格式的字符串(C#),c#,regex,string,validation,C#,Regex,String,Validation,我在SO上看到的大多数方法都涉及到验证C#date对象,这不是我想要做的。对于我正在处理的内容,用户将以一种格式输入一个字符串,例如1999-02-23。我想验证他们输入的字符串是否遵循YYYY-MM-DD格式。我提出的解决方案似乎过于复杂 试试看 var stringToValidate = "1999-02-23"; DateTime dt; bool ok = DateTime.TryParseExact( stringToValidate, "yyyy-MM-dd",

我在SO上看到的大多数方法都涉及到验证C#date对象,这不是我想要做的。对于我正在处理的内容,用户将以一种格式输入一个字符串,例如1999-02-23。我想验证他们输入的字符串是否遵循YYYY-MM-DD格式。我提出的解决方案似乎过于复杂

试试看

var stringToValidate = "1999-02-23";
DateTime dt;
bool ok = DateTime.TryParseExact(
   stringToValidate,
   "yyyy-MM-dd",
   CultureInfo.InvariantCulture,
   DateTimeStyles.None,
   out dt
);

免责声明:@AlexD-具有验证日期的正确方法。无法对
正则表达式执行相同操作,因为

然而,引述原问题:

我在SO上看到的大多数方法都涉及确认C#date 对象,这不是我想做的

由于问题也被标记为
regex
,这里有两种方法可以通过
regex
获得不同程度的部分成功:

日期时间相比,二月/四月/六月/九月/十一月无法生成有效的
日期时间。TryParseExact()

与闰年的
DateTime.TryParseExact()
相比,FEB无法生成有效的
DateTime

// single line Regex, formatted below for readability:
// "\d{3}[1-9]-(([0][13578]-(0[1-9]|1[012]|2\d|3[01]))|([0][469]-(0[1-9]|1[012]|2\d|30))|(02-(0[1-9]|1[012]|2[0-8]))|(11-(0[1-9]|1[012]|2\d|30))|(12-(0[1-9]|1[012]|2\d|3[01])))"
var regexAllButFeb = new Regex(
    @"
        # DateTime.MinValue => '0001-01-01'
        \d{3}[1-9]
        - 
        (
            # JAN / MAR / MAY / JUL/ AUG
            ([0][13578]-(0[1-9] | 1[012] | 2\d | 3[01]))
            | 
            # APR / JUN / SEP / NOV
            ([0][469]-(0[1-9] | 1[012] | 2\d | 30))
            |
            # FEB
            (02-(0[1-9] | 1[012] | 2[0-8]))
        #   or replace with [0-9] - ^^^^^
            |
            # NOV
            (11-(0[1-9] | 1[012] | 2\d | 30))
            |
            # DEC
            (12-(0[1-9] | 1[012] | 2\d | 3[01]))
        )
    ",
    RegexOptions.Compiled
    | RegexOptions.IgnorePatternWhitespace
);

希望上述内容与您尝试过的内容不同

DateTime.TryParseExact
很挑剔,但您想只验证字符串,还是验证字符串是否为有效日期(存在差异),或者实际将其解析为
DateTime
?这就是我一直在寻找的解决方案。非常感谢。
// single line Regex, formatted below for readability:
// "\d{3}[1-9]-(([0][13578]-(0[1-9]|1[012]|2\d|3[01]))|([0][469]-(0[1-9]|1[012]|2\d|30))|(02-(0[1-9]|1[012]|2[0-8]))|(11-(0[1-9]|1[012]|2\d|30))|(12-(0[1-9]|1[012]|2\d|3[01])))"
var regexAllButFeb = new Regex(
    @"
        # DateTime.MinValue => '0001-01-01'
        \d{3}[1-9]
        - 
        (
            # JAN / MAR / MAY / JUL/ AUG
            ([0][13578]-(0[1-9] | 1[012] | 2\d | 3[01]))
            | 
            # APR / JUN / SEP / NOV
            ([0][469]-(0[1-9] | 1[012] | 2\d | 30))
            |
            # FEB
            (02-(0[1-9] | 1[012] | 2[0-8]))
        #   or replace with [0-9] - ^^^^^
            |
            # NOV
            (11-(0[1-9] | 1[012] | 2\d | 30))
            |
            # DEC
            (12-(0[1-9] | 1[012] | 2\d | 3[01]))
        )
    ",
    RegexOptions.Compiled
    | RegexOptions.IgnorePatternWhitespace
);