[英]Extract Date and Time from a String Using Regex
我正在研究一種正則表達式,它接受日期和時間的所有可能格式以從句子中提取它們。
這是我的正則表達式:
@"(?:(?: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)";
當前,正則表達式在提取句子中任何位置的時間時都可以正常工作,但是僅在句子開頭時才提取日期。 另外,如果句子中有第二個日期,則正則表達式不會確認它,但是如果緊跟在日期旁邊的文本之后則有文本。
例如:
Meet me on 31/07/2019 at 3:00 PM to celebrate and then the meeting will be on 03/08/2019 at 12:00 PM.
正則表達式應該匹配:
1) 31/07/2019
2) 3:00 PM
3) 03/08/2019
4) 12:00 PM
注意:預期輸出應從句子的任何部分(開頭,中間,結尾)中提取
\\D*
+時間模式之前的正則表達式部分與各種類型的日期匹配,並且在添加任何其他模式之前必須將其分組。 也就是說, (?<date>DATE1_PATTERN|DATE2_PATTERN|DATEn_PATTERN)\\D*(?<time>TIME_PATTERN)
。
然后,匹配並訪問命名組:
var s = "Meet me on 31/07/2019 at 3:00 PM to celebrate and then the meeting will be on 03/08/2019 at 12:00 PM.";
var pattern = @"(?<date>(?:(?:31([-/.])(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:1|30)([-/.])(?:0?[13-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[AP]M)";
var result = Regex.Matches(s, pattern);
foreach (Match m in result) {
Console.WriteLine(m.Groups["date"].Value);
Console.WriteLine(m.Groups["time"].Value);
}
參見C#演示 ,輸出:
31/07/2019
3:00 PM
03/08/2019
12:00 PM
這是.NET正則表達式小提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.