gpt4 book ai didi

c# - 如何从字符串中解析日期?

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:49 24 4
gpt4 key购买 nike

我想从字符串中解析日期,其中日期格式可以是任何不同的格式。

现在我们可以使用 DateTime.TryParseExact 来匹配日期,我们可以根据需要定义格式,并且日期将匹配任何不同的格式。

string[] formats = {"MMM dd yyyy"};

DateTime dateValue;
string dateString = "May 26 2008";

if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))

MessageBox.Show(dateValue.ToString());

这与日期匹配。但这不适用于从字符串中解析日期,因为它与某些字符串中的日期不匹配。

喜欢如果日期是 "May 26 2008" 那么我们可以定义格式 "MMM dd yyyy" 并且日期将被匹配。

但是如果日期在一些字符串中,比如 "Abc May 26 2008" 那么日期将不会被匹配。那么我们可以在这里使用正则表达式吗?如果是怎么办?

我要解析日期的字符串是从 html 页面解析的,字符串可以是任何不同的。

编辑:我想使用正则表达式来编写与任何包含日期的字符串相匹配的格式。

最佳答案

您可以对诸如 @[A-Za-z]{3}\d{2}\d{4}" 之类的内容进行正则表达式匹配,并将任何匹配项提供给 DateTime.TryParseExact。它可能会因其他文化而中断,但是,我不确定周围是否有语言的月份名称只有 2 个短字母之类的:)

或者,您可以从 cultureInfo.DateTimeFormat.AbbreviatedMonthNames 中提取月份名称,并使用它来构建针对性更好的正则表达式。它也应该适用于其他文化。

编辑 - 这是一个例子:

string text = "Apr 03 2010 foo May 27 2008 bar";
CultureInfo ci = new CultureInfo("en-US");
Regex regex = new Regex(@"(?<date>(" + String.Join("|",
ci.DateTimeFormat.AbbreviatedMonthNames, 0, 12) + @") \d{2} \d{4})");

// Builds this regex:
// (?<date>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4})

var matches = regex.Matches(text);
foreach (Match match in matches)
{
string capturedText = match.Groups["date"].Value;
DateTime dt;
if (DateTime.TryParseExact(capturedText, "MMM dd yyyy", ci,
DateTimeStyles.None, out dt))
{
Console.WriteLine(capturedText + ": " + dt.ToLongDateString());
}
}

// Prints two parsed dates in long format

关于c# - 如何从字符串中解析日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com