11

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

4
  • @Bohemian, what I need to do is: check if the given string is valid, valid values are: 1D - 2D15H - 5H33M - 22D30M - 15D12H45M etc. Commented Nov 26, 2013 at 13:15
  • 1
    So all parts are optional, but there must be at least one part? Is 3D5M valid? Is there a maximum number value for the days part? Commented Nov 26, 2013 at 13:20
  • @Bohemian no there is not maximum for the days part Commented Nov 26, 2013 at 13:22
  • 1
    OK - see my updated answer that meets your extended requirements Commented Nov 26, 2013 at 13:29

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

Comments

1

A simplified regex can be:

^\\d{1,2}D\\d{1,2}H\\d{1,2}M$

2 Comments

thanks @anubhava for the answer, I have a question though, what does the numbers in the curly brackets mean?
\\d{1,2} means match 1 or 2 digits these numbers mean lower limit and upper limit of # of matched patterns.
1

Try,

    String regex = "\\d{1,2}D\\d{1,2}H\\d{1,2}M";
    String str = "25D8H15M";

    System.out.println(str.matches(regex));

6 Comments

It will also match 111125D8H15MMMM
@anubhava, nope, I have just tested.
String#matches adds ^ and $ but if same regex is used in Pattern then it will match bigger string.
@anubhava 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
@Masud the character classes are unnecessary here, ie \\d{1,2} is identical to [\\d]{1,2} because there's only one character (type)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.