0

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!

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
thqdqe
  • 3
  • 5
  • It is not clear to me what you consider acceptable. You write somewhere "no hour, minute, second", so you don't want a time component, but then why in your regex you mention "T"? Are you looking for `^P\d+[YMDW]$`? – trincot Sep 16 '22 at 22:40
  • @trincot I still don't want time component. only duration part should be accepted. I originally got this regex from https://rgxdb.com/r/MD2234J and I was playing with it, hoping it will work. I'm not super familiar with regex. – thqdqe Sep 16 '22 at 22:43
  • I don't understand what your requirements are. Like I said, why is there a "T" in your regex when you don't want it? Do you only want exactly one of Y, M, D, W? Then did you check my proposal? – trincot Sep 16 '22 at 22:46
  • @trincot Don't worry about my Regex. It's a bad one. On a side note. Y.ou got it right, your solution works. Thank you! – thqdqe Sep 16 '22 at 23:24
  • Do you want to allow durations with a minus sign? Like `-P1Y` or `P-1Y`or `-P0Y` or `P-0Y`? – Ole V.V. Sep 17 '22 at 12:16

1 Answers1

1

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

^P\d+[YMDW]$
trincot
  • 317,000
  • 35
  • 244
  • 286