Skip to content

Instantly share code, notes, and snippets.

@tristanls
Last active September 6, 2021 14:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristanls/356ce5aea0054b770d49 to your computer and use it in GitHub Desktop.
Save tristanls/356ce5aea0054b770d49 to your computer and use it in GitHub Desktop.
ISO-8601 Duration Regex
var iso8601durationregex = /^P([0-9]+(?:[,\.][0-9]+)?Y)?([0-9]+(?:[,\.][0-9]+)?M)?([0-9]+(?:[,\.][0-9]+)?D)?(?:T([0-9]+(?:[,\.][0-9]+)?H)?([0-9]+(?:[,\.][0-9]+)?M)?([0-9]+(?:[,\.][0-9]+)?S)?)?$/
@tristanls
Copy link
Author

Source: http://en.wikipedia.org/wiki/ISO_8601#Durations

Parses:

"P3Y6M4DT12H30M5S"
"P3,2Y6.5M4,7DT"
"PT57H30.5M3,77262S"

@deyhle
Copy link

deyhle commented Jun 15, 2021

The week designator is missing, so a valid ISO 8601 Duration like "P2W" (=2 Weeks") does not match.
I ended up using /^(-?)P(?=\d|T\d)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)([DW]))?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/ instead.

@tristanls
Copy link
Author

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment