c# - 我需要使用正则表达式从文本字符串中提取日期
问题描述
我需要更改我的正则表达式,以便之后能够在没有任何文本的情况下提取日期。目前,正则表达式提取日期和时间,但前提是它们一个接一个。如果它们之间有文本,则代码与该文本匹配。
我的正则表达式:
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# 程序,不要残忍:
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
推荐阅读
- nestjs - 在 Node 框架 NestJS-6.3.1 中面对 CORS
- python - 如何修复我的边界决策线?(Sklearn 和 python)
- python - 我正在尝试使用 python 连接到 mysql,但出现错误
- view - 在 javafxml 应用程序中初始化控制器时的空指针
- javascript - 是否有脚本可以将图表的 y 轴值更改为阿拉伯值?
- python - 有什么 pythonic 方式来清理这个字典列表?
- javascript - 如何从 HTML 中提取“有两个孩子的父母”模式
- php - 在数据透视表的页面上显示照片的问题
- filter - Crystal过滤中的记录选择公式过多
- python - 根据另一列的字符串删除列中的字符串