如何获取正则表达式匹配的组值

2022-08-31 16:36:46

我有以下代码行

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)

我在这里错过了什么吗?


答案 1

如果您避免呼叫,它可以正常工作。当您呼叫它时,会忘记任何以前的匹配项。matcher.replaceAllreplaceAll

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}))?";
Pattern pattern = Pattern.compile(timeRegex);
Matcher matcher = pattern.matcher(time);
if (matcher.matches()) {
    String hours = matcher.group(1);
    String minutes = matcher.group(2);
    String seconds = matcher.group(3);
    String miliSeconds = matcher.group(4);
    System.out.println(hours + ", " + minutes  + ", " + seconds + ", " + miliSeconds);
}

请注意,我还对正则表达式进行了一些改进:

  • 我已将非捕获组用于您不感兴趣的捕获组。(?: ... )
  • 我已经更改了哪个字符与任何仅匹配点的字符。.\\.

看到它在线工作:ideone


答案 2

如果在调用组函数之前使用,它可以工作。matcher.find()