【问题标题】:How to get regex matched group values如何获取正则表达式匹配的组值
【发布时间】: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吧?

标签: java regex


【解决方案1】:

如果您避免调用matcher.replaceAll,它可以正常工作。当您致电 replaceAll 时,它会忘记之前的任何匹配项。

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

【讨论】:

  • 当我实现这个时,我需要使用 matcher.find() 作为检查而不是 matcher.matches()。除此之外,这对我来说非常有效。
【解决方案2】:

如果你在调用组函数之前使用matcher.find(),它会起作用。

【讨论】:

  • 我遇到find返回true但组抛出异常的情况
猜你喜欢
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多