简体   繁体   中英

Regular Expressions Pattern Java

I'm still not sure how to deal with regular expressions. I have the following method that takes in a pattern and return the number of pictures that is taken in the year.

However, my method only takes in a perimeter year. I was intending to do something like String pattern = \\d + "/" + year; which means the month is a wildcard but only the year must be matched.

However, my code doesn't seem to work. Can someone guide me on regular expressions? The expected string to be passed in should be like "9/2014"

    // This method returns the number of pictures which were taken in the
    // specified year in the specified album. For example, if year is 2000 and
    // there are two pictures in the specified album that were taken in 2000
    // (regardless of month and day), then this method should return 2.
    // ***********************************************************************

    public static int countPicturesTakenIn(Album album, int year) {
        // Modify the code below to return the correct value.
        String pattern = \d + "/" + year;

        int count = album.getNumPicturesTakenIn(pattern);
        return count;
}

If I understand your question correctly, this is what you need:

public class SO {
public static void main(String[] args) {

    int count = countPicturesTakenIn(new Album(), 2016);
    System.out.println(count);
}

public static int countPicturesTakenIn(Album album, int year) {
    // Modify the code below to return the correct value.
    String pattern = "[01]?[0-9]/" + year;

    int count = album.getNumPicturesTakenIn(pattern);
    return count;
}

static class Album {
    private List<String> files;

    Album() {
        files = new ArrayList<>();
        files.add("01/2016");
        files.add("01/2017");
        files.add("11/2016");
        files.add("1/2016");
        files.add("25/2016");
    }

    public int getNumPicturesTakenIn(String pattern) {
        return (int) files.stream().filter(n -> n.matches(pattern)).count();
    }
}

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