需求:加班时间只能是0.5~24的数值,小数点只能是0或者5.
java端正则实现:
^([0](\\.[5]{1}){1})|((([1-9])|([1][0-9])|([2][0-3]))(\\.[0,5]{1})?)|(([2][4])(\\.[0]{1})?)$
代码:
static boolean isMatched(String target) {
Pattern pattern = Pattern.compile("^([0](\\.[5]{1}){1})|((([1-9])|([1][0-9])|([2][0-3]))(\\.[0,5]{1})?)|(([2][4])(\\.[0]{1})?)$");
Matcher match = pattern.matcher(target);
return match.matches();
}
在angular的ts文件中:
if (value.match(/^([0](\.[5]{1}){1})|((([1-9])|([1][0-9])|([2][0-3]))(\.[0,5]{1})?)|(([2][4])(\.[0]{1})?)$/)) {
return true;
}
却没有生效,分开写:
if(value.match(/^([0](\.[5]{1}){1})$/)){
return true;
}else if(value.match(/^((([1-9])|([1][0-9])|([2][0-3]))(\.[0,5]{1})?)$/)){
return true;
}else if(value.match(/^(([2][4])(\.[0]{1})?)$/)){
return true;
}
这样却可以。很是奇怪,后开才知道,是没有加空格的原因,这样写就可以了:
if (value.match(/^([0](\.[5]{1}){1}) | ((([1-9])|([1][0-9])|([2][0-3]))(\.[0,5]{1})?) | (([2][4])(\.[0]{1})?)$/)) {
return true;
}
实践出真知。