欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

判断时间的正则表达式

程序员文章站 2022-03-27 10:24:57
普通方法为,分离出小时、分钟、秒分别进行判断: public static boolean timecheck(string time, string owner) { /...
普通方法为,分离出小时、分钟、秒分别进行判断:
public static boolean timecheck(string time, string owner) {
//检查时间字符串time是否满足格式“hh:mm:ss”或“hh:mm”,若不满足显示相应消息,并返回false
if(time.equals("")){
string msg = owner+" : "+"time is empty.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
int hours, minutes, seconds = 0;
stringtokenizer st = new stringtokenizer(time, ":");
int tokens = st.counttokens();
if (tokens != 3 && tokens != 2) {
string msg = owner+" : "+"time " + time + " does not conform to the hh:mm:ss format, nor hh:mm format.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
string hourtoken = st.nexttoken();
try {
hours = integer.parseint(hourtoken);
} catch (numberformatexception nfe) {
string msg = owner+" : "+hourtoken + " in " + time + " can not be parsed as hours.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
string minutetoken = st.nexttoken();
try {
minutes = integer.parseint(minutetoken);
} catch (numberformatexception nfe) {
string msg = owner+" : "+minutetoken + " in " + time + " can not be parsed as minutes.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
if(tokens == 3){
string secondtoken = st.nexttoken();
try {
seconds = integer.parseint(secondtoken);
} catch (numberformatexception nfe) {
string msg = owner+" : "+secondtoken + " in " + time + " can not be parsed as seconds.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
}
if (hours < 0 || hours > 23) {
string msg = owner+" : "+"specified hours: " + hours + ". number of hours must be in the [0..23] range.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
if (minutes < 0 || minutes > 59) {
string msg = owner+" : "+"specified minutes: " + minutes + ". number of minutes must be in the [0..59] range.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
if (seconds < 0 || seconds > 59) {
string msg = owner+" : "+"specified seconds: " + seconds + ". number of seconds must be in the [0..59] range.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
return true;
}
正则方法为:
public static boolean timecheck(string time, string owner) {
//检查时间字符串time是否满足格式“hh:mm:ss”,若不满足显示相应消息,并返回false
string regex = "(([01]\\d)|(2[0-3])):[0-5]\\d(:[0-5]\\d)?";
if(!time.matches(regex)){
string msg = owner+" : "+"time is invalid.";
messagedialog.showerror(controller.getmainframe(), msg);
return false;
}
return true;
}
  真是很好很强大啊!!不过上述正则“((2[0-3])|([01]\d)):[0-5]\d(:[0-5]\d)?”实现居然不能匹配“3:3:3”,郁闷!
  将正则改为“((2[0-3])|([0-1]?\d)):[0-5]?\d(:[0-5]?\d)?”倒是可以匹配“3:3:3”这种了,但“3:65:34”显然是不对的,却又匹配出两个来,晕!
  将正则改为“((2[0-3])|([0-1]?\d)):[0-5]?\d(:[0-5]?\d)”倒是可以匹配“3:3:3”,也能正确判断“3:65:34”,却又没法判断“3:34”这种格式了。唉~~~~