Extract Date and Time from a String Using Regex

前端 未结 1 1172
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-25 22:35

I am working on a regex that accepts all possible formats of date and time to extract them from a sentence.

This is my Regex:

@\"(?:(?:31(\\/|-|\\.)(?:0?         


        
相关标签:
1条回答
  • 2021-01-25 23:41

    Your regex part before the \D* + time pattern matches various types of dates, and must be grouped before adding any other pattern to follow. That is, (?<date>DATE1_PATTERN|DATE2_PATTERN|DATEn_PATTERN)\D*(?<time>TIME_PATTERN).

    Then, just match and access named groups:

    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);
    }
    

    See the C# demo, output:

    31/07/2019
    3:00 PM
    03/08/2019
    12:00 PM
    

    Here is the .NET regex fiddle.

    0 讨论(0)
提交回复
热议问题