Java正则表达式不会返回捕获组

时间:2016-07-29 03:27:35

标签: java regex

在Java中,我想使用正则表达式以“MM / DD / YYYY”格式解析日期字符串。我尝试用括号创建捕获组,但它似乎不起作用。它只返回整个匹配的字符串 - 而不是“MM”,“DD”和“YYYY”组件。

public static void main(String[] args) {
    Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})");
    Matcher m1=p1.matcher("04/30/1999");

    // Throws IllegalStateException: "No match found":
    //System.out.println("Group 0: "+m1.group(0));

    // Runs only once and prints "Found: 04/30/1999".
    while (m1.find()){
        System.out.println("Found: "+m1.group());
    }
    // Wanted 3 lines: "Found: 04", "Found: 30", "Found: 1999"
}

带有参数(group)的“m1.group(x)”函数似乎根本不起作用,因为无论我给出什么索引它都会返回异常。循环find()仅返回单个整个匹配“04/30/1999”。正则表达式中的括号似乎完全没用!

在Perl中这很容易做到:

my $date = "04/30/1999";
my ($month,$day,$year) = $date =~ m/(\d{2})\/(\d{2})\/(\d{4})/;
print "Month: ",$month,", day: ",$day,", year: ",$year;
# Prints:
#     Month: 04, day: 30, year: 1999

我错过了什么? Java正则表达式是否无法解析Perl中的捕获组?

1 个答案:

答案 0 :(得分:3)

先呼叫m1.find(),然后使用m1.group(N)

matcher.group()matcher.group(0)会返回整个匹配的文字 matcher.group(1)返回第一组匹配的文字 matcher.group(2)返回第二组匹配的文字 ...

<强>代码

Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})");
Matcher m1=p1.matcher("04/30/1999");

if (m1.find()){ //you can use a while loop to get all match results
    System.out.println("Month: "+m1.group(1)+" Day: "+m1.group(2)+" Year: "+m1.group(3));
}

<强>结果

Month: 04 Day: 30 Year: 1999

ideone demo