从字符串中获取日期

9
假设我有以下字符串之一:
"Hello, I'm a String... This is a Stackoverflowquestion!! Here is a Date: 16.03.2013, 02:35 and yeah, plain text blah blah..-."

"This the other string! :) 22.11.2012. Its a Date you see"

"Here we have 2 Dates, 23.12.2012 and 14.07.2011"

如何最快最好地从字符串(在 DateTime 中)中获取这些日期?

(仅返回字符串中第一个出现的日期)

期望的返回结果:

String 1: 16.03.2013 (as a DateTime)
String 2: 22.11.2012 ("           ")
String 3: 23.12.2012 ("           ")

那么我会调用一个方法,例如:

DateTime date1 = GetFirstDateFromString(string1);

1
这似乎是一个需要用正则表达式解决的问题! - Broken_Window
1
如果这些日期格式是特定于某种文化的,您可以提取日期格式并使用正则表达式搜索字符串。 - myermian
它们是的。它们总是以这种格式出现。 - eMi
5个回答

20

这将从输入文本中提取、解析并打印所有的日期:

var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
    DateTime dt;
    if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
        Console.WriteLine(dt.ToString());
}

现在,如果您只想要第一个日期,您可以这样做:

static DateTime? GetFirstDateFromString(string inputText)
{
    var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
    foreach(Match m in regex.Matches(inputText))
    {
        DateTime dt;
        if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
            return dt;
    }
    return null;
}

需要注意的是该方法返回一个可空的DateTime,因此当字符串不包含日期时它可以返回null


这将在例如“58.99.2013”上失败。 - Ant P
@MartinMulder,不,它不会匹配;它将只是跳过并处理下一个匹配项。 - Thomas Levesque
@ThomasLevesque,我尝试了这个解决方案,使用正则表达式进行dd-MMM-yyyy格式的修改,但对我来说不起作用。您能否帮助我从以下字符串中获取日期 “8周小组辅导-2021年11月07日至2021年12月31日(上午05:00:00至上午06:00:00)” - Manish Nayak
1
@ManishNayak,使用以下正则表达式应该可以工作:@"\b\d{2}-[A-Za-z]{3}-\d{4}\b"。此外,您可能应该使用不变或en-US文化作为“provider”参数。 - Thomas Levesque
@ThomasLevesque 谢谢您的帮助,@"\b\d{2}-[A-Za-z]{3}-\d{4}\b" 对我有用 :) - Manish Nayak
显示剩余2条评论

7
如果你的日期总是以那种格式出现,你可以尝试使用正则表达式来获取日期字符串,然后使用 DateTime.ParseExact 方法得到想要的结果:
public DateTime? GetFirstDateFromString(string input)
{
    DateTime d;

    // Exclude strings with no matching substring
    foreach (Match m in Regex.Matches(input, @"[0-9]{2}\.[0-9]{2}\.[0-9]{4}"))
    {
        // Exclude matching substrings which aren't valid DateTimes
        if (DateTime.TryParseExact(match.Value, "dd.MM.yyyy", null, 
            DateTimeStyles.None, out d))
        {
            return d;
        }
    }
    return null;
}

@JimMischel 哎呀!本来复制好了,但是忘记粘贴了!现在完成了。 - Ant P
如果字符串中出现58.99.2013并位于实际日期之前,将会失败。 - Martin Mulder
这里我遇到了一些问题...如果返回类型不可为空,就不能返回null。第二件事是,变量“enUS”没有定义在任何地方。我宁愿使用CultureInfo.CurrentCulture,但还是感谢你的努力!加1分! - eMi
真的 - 我已经解决了这些问题。 - Ant P

1

试试这个:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static DateTime? GetFirstDateFromString(string input);
   {
      string pattern = @"\d{2}\.\d{2}\.\d{4}";
      Match m = Regex.Match(input, pattern);
      DateTime result;
      foreach(string value in match.Groups)  
          if (DateTime.TryParseExact(match.Groups[1], "dd.MM.yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)
              return result;
      return null;
   }
}

例如,这将在“58.99.2013”上失败。 - Ant P
已调整!现在它会搜索第一个匹配的日期/时间,否则返回 null。 - Martin Mulder

1

对于我来说,这段代码可以从包含日期的文本中获取日期。

var regex = new Regex(@"\d{2}\/\d{2}\/\d{4}");
 foreach (Match m in regex.Matches(line))
 {
  DateTime dt;
  if (DateTime.TryParseExact(m.Value, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
  remittanceDateArr[chequeNo - 1] = dt.ToString("MM/dd/yyyy");                                   
  rtbExtract.Text = rtbExtract.Text + remittanceDateArr[chequeNo - 1] + "\n";
                            }

0
创建一个方法,其参数是用于捕获日期格式的正则表达式和要从中提取日期的字符串。我认为,如果您没有将要使用的格式,则无法从字符串中的一系列字母数字字符中提取日期。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接