【发布时间】:2012-07-24 20:47:03
【问题描述】:
我有以下代码行
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)
我错过了什么吗?
【问题讨论】:
-
只是为了确定,你还是先检查
matcher.matches() == True吧?