首页 > 解决方案 > 我需要使用正则表达式从文本字符串中提取日期

问题描述

我需要更改我的正则表达式,以便之后能够在没有任何文本的情况下提取日期。目前,正则表达式提取日期和时间,但前提是它们一个接一个。如果它们之间有文本,则代码与该文本匹配。

我的正则表达式:

string pattern = @"(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:1|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:[\D]*)(?<time>\d{1,2}\:\d{2}\s(?:A|P)M)";

这句话应该是这样的:

Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.

正则表达式应匹配:

1)5/1/2019

2)6:32 PM

3)5/2/2019

4)7:32 PM

目前,这是输出的样子:

Parsed 'Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.' to 5/1/2019 at 6:32 PM.
Unable to convert 'Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.' to a date.
Parsed 'Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.' to 5/2/2019 7:32 PM.
Converted 'Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.' to 05/02/2019 19:32:00.

注意事项

2019年5 月 1至 6:32 之间的时间已被接受,但不应如此。

请让任何答案与我的正则表达式有些相关,因为它是使用它的要求。

标签: c#regex

解决方案


这是我的第一个 c# 程序,不要残忍:

using System;
using System.Text.RegularExpressions;

namespace myApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Hello, meet me 5/1/2019 at 6:32 PM and then 5/2/2019 7:32 PM bye.";
            Regex word = new Regex(@"(([0-9]{1,2}:[0-9]{1,2}\s[A-Z]{2})|([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}))");
            MatchCollection mc = word.Matches(input);
            foreach (Match m in mc)
            {
                Console.WriteLine(m);
            }
        }
    }
}

输出:

5/1/2019
6:32 PM
5/2/2019
7:32 PM

推荐阅读