Home > Software design >  Regex expression for ISO 8601 duration
Regex expression for ISO 8601 duration

Time:09-17

I've been looking at ISO 8061 Wikipedia - https://en.wikipedia.org/wiki/ISO_8601#Durations

I want to create a regex so that:

Allowed Input

P1Y // date component only
P5W 

Not Allowed Input

P1Y5W // No Year, month, week together. Just one of them.
P1Y2DT0H3M // No hour, minute, second

I tried

/^(-?)P(?=\d|T\d)(?:(\d )Y)?(?:(\d )M)?(?:(\d )([DW]))/

P1Y2DT0H3M didn't pass while P1Y2D(shouldn't pass either)

What should I do?

Thank you in advance!

CodePudding user response:

As you only want one period specifier that is either Y, M, D or W, you can use this regex:

^P\d [YMDW]$
  • Related