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
3 Answers
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.
Comments
A simplified regex can be:
^\\d{1,2}D\\d{1,2}H\\d{1,2}M$
2 Comments
\\d{1,2} means match 1 or 2 digits these numbers mean lower limit and upper limit of # of matched patterns.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
111125D8H15MMMMString#matches adds ^ and $ but if same regex is used in Pattern then it will match bigger string.String.matches() must match the whole string, so start and end are implied\\d{1,2} is identical to [\\d]{1,2} because there's only one character (type)
3D5Mvalid? Is there a maximum number value for the days part?