Serhii
Serhii

Reputation: 7563

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.

Upvotes: 2

Views: 1293

Answers (3)

sniperd
sniperd

Reputation: 5274

Here is a very generic and simple regex that should do the trick:

(\d+)T?(\d*)

It captures any numbers up to the first optional T. Then if there are more numbers afterwards, it gets those too. Here is a little Python example with the out as requested.

thelist = ["19960404T010000Z",
"19960404T010000",
"19960404T",
"19960404",]

for i in thelist:
    thematch = re.search("(\d+)T?(\d*)", i)
    if thematch.group(2):
        print ((thematch.group(1)) + "|" + thematch.group(2))
    else:
        print ((thematch.group(1)) + "|")

Upvotes: 2

dwaskowski
dwaskowski

Reputation: 425

For checking regex you could use page: https://regex101.com

(\d{8})T?(\d{6})?Z?

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

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

Upvotes: 3

Related Questions