Check if a String matches specific regular expression

java, regex, string

Solution

Here's the briefest way to code the regex:

if (str.matches("(?!$)(\\d+D)?(\\d\\d?H)?(\\d\\d?M)?"))
    // format is correct

This allows each part to be optional, but the negative look ahead for end-of-input at the start means there must be something there.

Note how with java you don't have to code the start (`^`) and end (`$`) of input, because `String.matches()` must match the whole string, so start and end are implied.

However, this is just a rudimentary regex, because `99D99H99M` will pass. The regex for a valid format would be:

if (str.matches("(?!$)(\\d+D)?([0-5]?\\dH)?([0-5]?\\dM)?"))
    // format is correct

This restricts the hours and minutes to `0-59`, allowing an optional leading zero for values in the range `0-9`.

Problem

I am not so good with regular expressions and stuff, so I need help. I have to check if a input value matches a specific regular expression format. Here is the format I want to use, `25D8H15M`. Here the `D` means the # of days `H` means hours and `M` means minutes. I need the regular expression to check the String. Thanks

Original source