[英]Check if a String matches specific regular expression
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
.这是我要使用的格式
25D8H15M
。 Here the D
means the # of days H
means hours and M
means minutes.这里
D
表示天数H
表示小时, M
表示分钟。 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 .请注意如何使用 java 您不必对输入的开始 (
^
) 和结束 ( $
) 进行编码,因为String.matches()
必须匹配整个字符串,所以开始和结束是隐含的。
However, this is just a rudimentary regex, because 99D99H99M
will pass.然而,这只是一个基本的正则表达式,因为
99D99H99M
会通过。 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
.这将小时和分钟限制为
0-59
,允许为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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.