ISO 8601 Duration Regex for Go
/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching iso 8601 duration, ported and verified for Go. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// ISO 8601 Duration
// ReDoS-safe | RegexVault — Localization > Date Formats
package validation
import "regexp"
var iso8601DurationRe = regexp.MustCompile(`^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$`)
func ValidateIso8601Duration(s string) bool {
return iso8601DurationRe.MatchString(s)
}
// Example
// fmt.Println(ValidateIso8601Duration("P1Y")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
P1Y | P |
P1Y2M3D | PT |
PT1H30M | 1Y |
P1Y2M3DT4H5M6S | P1YT |
P30D | P1Y2M3DT |
PT0.5S | — |
P1W | — |
When to use this pattern
This pattern is drawn from the Localization > Date Formats category and carries a ReDoS-safe certification. That matters for Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
ISO 8601 specifies that W (weeks) cannot be combined with Y, M, or D components. This pattern allows the combination — enforce the restriction at application level if strict compliance is required.
Technical Notes
Lookahead (?!$) ensures at least one component is present. Capture groups: 1=years, 2=months, 3=weeks, 4=days, 5=hours, 6=minutes, 7=seconds. Weeks (W) cannot be combined with other date components in strict ISO 8601.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern