我有以下的代码如何获得正则表达式匹配的组值
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