我有以下的代碼如何獲得正則表達式匹配的組值
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',對吧? – 2012-07-26 09:36:02