我有一个字符串变量定义为:
string str = Request[columns[2][search]];
有时 str
返回值 AR
有时 15/02/2018 到 23/04/2018
因此我正在检查 str
是否包含 15/02/2018 到 23/04/2018
,然后它应该返回 true。
为了执行此检查,我使用了以下代码,但它似乎不起作用。它总是返回给我 false
。有人可以帮我解决这个问题或使用正则表达式作为替代方案吗?
DateTime date;
Boolean isValidDate = DateTime.TryParseExact(str, "dd/MM/yyyy to dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
最佳答案
我会分两次完成:
- 如果日期存在,则使用正则表达式提取日期。
- 使用
DateTime.TryParseExact
检查每个日期是否真的是一个日期。
我建议不要尝试在正则表达式本身中进行完整的日期验证 - 这更多的是在 DateTime
域中。正则表达式域更像是“找到可能是日期的文本位”。
这是此方法的完整示例:
using System;
using System.Globalization;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Test("AR");
Test("99/99/9999 to 99/99/9999");
Test("15/02/2018 to 23/04/2018");
}
static void Test(string text)
{
var result = TryParseDates(text, out var from, out var to);
Console.WriteLine(result
? $"{text}: match! From={from:yyyy-MM-dd}; To={to:yyyy-MM-dd}"
: $"{text}: no match");
}
static readonly Regex dateToDatePattern = new Regex(@"^(\d{2}/\d{2}/\d{4}) to (\d{2}/\d{2}/\d{4})$");
static bool TryParseDates(string text, out DateTime from, out DateTime to)
{
var match = dateToDatePattern.Match(text);
if (match.Success)
{
// Don't assign values to the out parameters until we know they're
// both valid.
if (DateTime.TryParseExact(match.Groups[1].Value, "dd/MM/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempFrom)
&&
DateTime.TryParseExact(match.Groups[2].Value, "dd/MM/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempTo))
{
from = tempFrom;
to = tempTo;
return true;
}
}
// Either the regex or the parsing failed. Either way, set
// the out parameters and return false.
from = default(DateTime);
to = default(DateTime);
return false;
}
}
输出:
AR: no match
99/99/9999 to 99/99/9999: no match
15/02/2018 to 23/04/2018: match! From=2018-02-15; To=2018-04-23
关于c# - 检查字符串是否包含 C# 中日期形式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953280/