简体   繁体   中英

Java regex won't return capture groups

In Java, I want to use a regular expression parse a date string in the format "MM/DD/YYYY". I tried making capture groups with parentheses, but it doesn't seem to work. It only returns the entire matched string -- not the "MM", "DD", and "YYYY" components.

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

The " group " function that takes an argument ( m1.group(x) ) doesn't seem to work at all, as it returns an exception no matter what index I give it. Looping over the find() 's only returns the single whole match "04/30/1999". The parentheses in the regular expression seem to be completely useless!

This was pretty easy to do in 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

What am I missing? Are Java regular expressions unable to parse out capture groups like in Perl?

Call m1.find() first, then use m1.group(N)

matcher.group() or matcher.group(0) return the whole matched text.
matcher.group(1) returns the text matched by the first group.
matcher.group(2) returns the text matched by the second group.
...

Code

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));
}

Result

Month: 04 Day: 30 Year: 1999

ideone demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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