String仅包含给定的一组字符

Ter*_*ver 21 c# regex

我需要知道给定的字符串是否是有效的DateTime格式字符串,因为字符串可能代表其他东西.我试图DateTime.ParseExact(somedate.ToString(格式)格式),认为它会BARF上是无效的格式,但它没有.

所以我很擅长测试字符串是否只包含"yYmMdDsShH"字符.像std :: string.find_first_not_of这样的东西可以工作,但System.String没有这个.

我认为RegEx可以做到这一点,但我对正则表达式非常弱.

请注意,Linq不适用于此版本(仅限.NET 2.0).

更新

为了澄清,我需要知道给定的字符串是否代表日期时间格式,而不是像这样:

if (input == "some special value")
... // it's a special case value
else if (Environment.GetEnvironmentVariable(input))
... // it's an environment variable name
else if (IsDateTimeFormatString(input))
... // it's a date time format string
else if (input.IndexOfAny(Path.GetInvalidPathChars()) < 0)
... // it's a file path
else
   throw new Exception(); // Not a valid input
Run Code Online (Sandbox Code Playgroud)

我可以将DateTime格式字符串限制为仅仅"yYmMdDsShH",或者我也可以在其中添加一些分隔符,这取决于我允许或不允许的内容.

Ree*_*sey 36

使用.NET2,您需要为此进行自己的检查.例如,以下方法使用foreach来检查:

bool FormatValid(string format)
{
    string allowableLetters = "yYmMdDsShH";

    foreach(char c in format)
    {
         // This is using String.Contains for .NET 2 compat.,
         //   hence the requirement for ToString()
         if (!allowableLetters.Contains(c.ToString()))
              return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果您可以选择使用.NET 3.5和LINQ,则可以使用Enumerable.Contains直接处理字符和Enumerable.All.这将简化以上内容:

bool valid = format.All(c => "yYmMdDsShH".Contains(c));
Run Code Online (Sandbox Code Playgroud)

  • @MikeD:这就是为什么我的实现不使用它;)它是一个纯.NET 2实现.我刚刚提到LINQ让这很容易...... (2认同)

SLa*_*aks 19

像这样:

static readonly Regex Validator = new Regex(@"^[yYmMdDsShH]+$");

public static bool IsValid(string str) {
    return Validator.IsMatch(str);
}
Run Code Online (Sandbox Code Playgroud)

正则表达式的工作方式如下:

  • ^ 匹配字符串的开头
  • [...] 匹配括号中出现的任何字符
  • + 匹配与前一项匹配的一个或多个字符
  • $ 匹配字符串的结尾

如果没有^和$锚,正则表达式将匹配包含至少一个有效字符的任何字符串,因为正则表达式可以匹配字符串的任何子字符串使用它.在^与$锚迫使它整个字符串相匹配.