Home > Net >  Regex for ISO8601 temporal duration but only with minutes and seconds
Regex for ISO8601 temporal duration but only with minutes and seconds

Time:01-21

I'm attempting to write Regex to match the ISO8601 standard for temporal durations, but only where PT and M or S are valid.

So far I have found a full example of ISO8601 regex but it is more complex than I need. I need match durations like the following:

  • PT7S
  • PT10M50S
  • PT150S

Essentially I want the Regex to always check that:

  • capitalised PT is at the beginning of the string
  • M is preceded by a whole number
  • S is preceded by a whole number
  • M comes before S

My attempt so far:

  • capitalised PT at the beginning = ^PT
  • M preceded by a whole number = [0-9] M - except this allows something like 10.5M because the 5M counts
  • S preceded by a whole number = same as above
  • M comes before S. Again no idea!

I'm really stuck on trying to figure this out, I've been trying to get each part to match so I could try and combine them all later but I can't get over the first hurdle.

CodePudding user response:

Shouldn't be much more complex than

const rxIso8601Duration = /^PT((([0-9] M)?([0-9] S))|([0-9] M))$/ ;

Breaking it down:

^              // - anchor the match at start-of-text, followed by
PT             // - the literal PT, followed by
(              // - a group, consisting of either
  (            //   - a group, consisting of
    ([0-9] M)? //     - an optional minutes designation, followed by
    ([0-9] S)  //     - a required seconds designation
  )            //
  |            //   or
  ([0-9] M)    //     - a required minutes designation
)              // the whole of which is followed by
$              // end-of-text

If you want to allow fractional minutes or seconds, Just change the appropriate sub-expression(s):

  • ([0-9] M)
    recognizes patterns like 123M, but not 123.456M
  • ([0-9] (\.[0-9] )?M)
    will recognize not only 123M but also matches 123.456M
  •  Tags:  
  • Related