Regex HHmm validation- Java



我需要验证一个包含时间的textBox条目。

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

例如:

09:00, 21:00, 00:00, etc.,

无效条目:

2534, 090, *7&**, etc.,

如果输入的时间是HHmm格式,那么我需要附加一个":"到条目。

例如:

If textBox entry= 0930, it should be changed to 09:30

这就是我目前所拥有的:

String textBoxVal = getTextBoxValue();
String colonCheck = ":";
if (!textBoxVal.contains(colonCheck)){
textBoxVal = textBoxVal.substring(0,2) + ":" + textBoxVal.substring(2,4);
}

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

我对regex不是很熟悉,所以任何关于如何在Java中使用regex实现这一点的帮助都会很有帮助!谢谢

Ranhiru 指出的使用DateFormat的解决方案

    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);
    }

以下将为您提供

str = str.replaceAll("([01][0-9]|[2][0-3]):?([0-5]d)", "$1:$2");

这将从2300更改为23:00,并按原样保留23:00。

您也可以仅使用(?:[01][0-9]|[2][0-3]):?[0-5]d进行验证。

还有一点需要注意的是,即使这一个成功了,如果你想要的是日期验证,那么我会选择DateFormat路线。

//Assuming text to match is in var mytext
var re=new RegExp(/^(dd):{0,1}(dd)$/);
var match=re.exec(mytext);
if (!match) alert("Bad value!");
else mytext=match[1]+':'+match[2];

最新更新