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)
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 stringWithout 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.