正则表达式HHmm验证 - Java

use*_*523 1 java regex string validation time

我需要验证包含时间的textBox条目.

时间应为HH:mm格式和24小时格式.

例如:

09:00, 21:00, 00:00, etc.,
Run Code Online (Sandbox Code Playgroud)

无效的条目:

2534, 090, *7&**, etc.,
Run Code Online (Sandbox Code Playgroud)

如果输入的时间是HHmm格式,那么我需要在条目中附加一个':'.

例如:

If textBox entry= 0930, it should be changed to 09:30
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

String textBoxVal = getTextBoxValue();
String colonCheck = ":";

if (!textBoxVal.contains(colonCheck)){
textBoxVal = textBoxVal.substring(0,2) + ":" + textBoxVal.substring(2,4);
}
Run Code Online (Sandbox Code Playgroud)

但很明显,这段代码并不适用于所有情况.

我对正则表达式不是很熟悉,所以对于如何使用Java中的正则表达式来实现这一点的任何帮助都会有所帮助!谢谢!

Rog*_*cia 6

使用DateFormat的解决方案,正如Ranhiru指出的那样

    String theTime = "23:55";

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); //HH = 24h format
    dateFormat.setLenient(false); //this will not enable 25:67 for example
    try {
        System.out.println(dateFormat.parse(theTime));
    } catch (ParseException e) {
        throw new RuntimeException("Invalid time "+theTime, e);
    }
Run Code Online (Sandbox Code Playgroud)