简体   繁体   English

正则表达式模式 Java

[英]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;我打算做一些类似String pattern = \\d + "/" + year;事情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"要传入的预期字符串应类似于“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();
    }
}

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

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