String contains only a given set of characters

前端 未结 7 1418
执笔经年
执笔经年 2021-02-18 13:22

I need to know if a given string is a valid DateTime format string because the string may represent other things. I tried DateTime.ParseExact(somedate.ToString(format), format)

7条回答
  •  有刺的猬
    2021-02-18 14:02

    Like this:

    static readonly Regex Validator = new Regex(@"^[yYmMdDsShH]+$");
    
    public static bool IsValid(string str) {
        return Validator.IsMatch(str);
    }
    

    The regex works like this:

    • ^ matches the beginning of the string
    • [...] matches any of the characters that appear in the brackets
    • + matches one or more characters that match the previous item
    • $ matches the end of the string

    Without the ^ and $ anchors, the regex will match any string that contains at least one valid character, because a regex can match any substring of the string use pass it. The ^ and $ anchors force it to match the entire string.

提交回复
热议问题