正则表达式模式Java

时间:2016-09-22 14:02:18

标签: java

我还不确定如何处理正则表达式。 我有以下方法,它接受一个模式并返回一年中拍摄的图片数量。

但是,我的方法只需要一个周长。 我本打算做点什么 String pattern = \d + "/" + year;表示月份是通配符,但只有年份必须匹配。

但是,我的代码似乎不起作用。 有人可以指导我正则表达式吗? 要传入的预期字符串应该类似于" 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;
}

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这就是你需要的:

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