Search code examples
regexstring-matching

Parsing date and dateTime using regular expression in separate matchers


I need regular expression to parse date and time in separate way in my logic.

I tried use next pattern:

^(\d{8})+(?:T((\d{6})[^Z])?).*$

My expectation for input data

19960404T010000Z
19960404T010000
19960404T
19960404

is

group1   | group2
-----------------
19960404 | 010000
19960404 | 010000
19960404 | 
19960404 |

Can someone check my pattern issue (it does not work as expected)? To save your time I've prepared example using regex checker.


Solution

  • You may use

    ^(\d{8})(?:T(?:(\d{6})Z?)?)?$
    

    See the regex demo

    Details

    • ^ - start of string
    • (\d{8}) - Group 1: eight digits
    • (?:T(?:(\d{6})Z?)?)? - an optional sequence of
      • T - a T
      • (?:(\d{6})Z?)? - an optional sequence of
        • (\d{6}) - Group 2: six digits
        • Z? - an optional Z
    • $ - end of string