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

本文关键字:YYYY-MM-DD 形式 字符串 验证 何验证 | 更新日期: 2023-09-27 18:33:33

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

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

尝试

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

责声明:@AlexD - 具有验证日期的正确方法。您不能Regex执行相同的操作,因为闰年需要计算。

但是,引用原始问题:

我在SO上看到的大多数方法都涉及验证C#日期 对象,这不是我想做的。

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

DateTime.TryParseExact()相比,2 月/

4 月/6 月/9 月/11 月未能产生有效的DateTime

// single line Regex, formatted below for readability:
// "'d{3}[1-9]-(0[1-9]|1[012])-(0[1-9]|1'd|2'd|3[01])"
var regexSimple = new Regex(
    @"
        # DateTime.MinValue => '0001-01-01'
        'd{3}[1-9]
        - 
        (0[1-9] | 1[012])
        -
        (0[1-9] | 1'd | 2'd | 3[01])
    ",
    RegexOptions.Compiled
    | RegexOptions.IgnorePatternWhitespace
);

与闰年的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
);

希望以上不是您尝试过的相同内容。 ;)