gpt4 book ai didi

java - 正则表达式 HHmm 验证 - Java

转载 作者:行者123 更新时间:2023-11-29 10:05:33 24 4
gpt4 key购买 nike

我需要验证包含时间的文本框条目。

时间应为 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);
}

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

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

最佳答案

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

关于java - 正则表达式 HHmm 验证 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9242164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com