簡體   English   中英

正則表達式模式 Java

[英]Regular Expressions Pattern Java

我仍然不確定如何處理正則表達式。 我有以下方法,它接受一個模式並返回當年拍攝的照片數量。

然而,我的方法只需要一個周長年。 我打算做一些類似String pattern = \\d + "/" + year;事情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;
}

如果我正確理解您的問題,這就是您所需要的:

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