繁体   English   中英

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

[英]Java regex won't return capture groups

在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"
}

带有参数( m1.group(x) )的“ group ”函数似乎根本不起作用,因为无论我给它提供什么索引,它都会返回一个异常。 循环遍历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一样解析捕获组?

首先调用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演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM