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
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
.
简化的正则表达式可以是:
^\\d{1,2}D\\d{1,2}H\\d{1,2}M$
Try,
String regex = "\\d{1,2}D\\d{1,2}H\\d{1,2}M";
String str = "25D8H15M";
System.out.println(str.matches(regex));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.