我有以下代码行
String time = "14:35:59.99";
String timeRegex = "(([01][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])(.([0-9]{1,3}))?";
String hours, minutes, seconds, milliSeconds;
Pattern pattern = Pattern.compile(timeRegex);
Matcher matcher = pattern.matcher(time);
if (matcher.matches()) {
hours = matcher.replaceAll("$1");
minutes = matcher.replaceAll("$4");
seconds = matcher.replaceAll("$5");
milliSeconds = matcher.replaceAll("$7");
}
我使用matcher.replace
正则表达式组的方法和反向引用来获取小时、分钟、秒和毫秒。有没有更好的方法来获得正则表达式组的价值。我试过了
hours = matcher.group(1);
但它会引发以下异常:
java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:477)
at com.abnamro.cil.test.TimeRegex.main(TimeRegex.java:70)
我在这里错过了什么吗?