REGEXVAULT
Localization/Date Formats
ReDoS Checked

ISO 8601 Duration Regex for Java

/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/

All five implementations are free. Switch engines without signing in.

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching iso 8601 duration, ported and verified for Java. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// ISO 8601 Duration
// ReDoS-checked | RegexVault — Localization > Date Formats

import java.util.regex.Pattern;

public class Iso8601DurationValidator {
    private static final Pattern PATTERN =
        Pattern.compile("^P(?!$)(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?!$)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("P1Y")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
P1YP
P1Y2M3DPT
PT1H30M1Y
P1Y2M3DT4H5M6SP1YT
P30DP1Y2M3DT
PT0.5S
P1W

When to use this pattern

This pattern is drawn from the Localization > Date Formats category and has been checked for ReDoS risk. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. 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. Submissions join the review queue after automated validation.

Submit a Pattern