2016-09-22 80 views
-5

我還不確定如何處理正則表達式。 我有以下方法,它會採用一種模式並返回一年中拍攝的圖片數量。正則表達式模式Java

但是,我的方法只需要一個周長。 我打算做一些像 String pattern = \d + "/" + year;這意味着該月是一個通配符但只有一年必須匹配。

但是,我的代碼似乎不工作。 有人可以指導我正則表達式嗎? 要傳遞的預期字符串應該是像「2014分之9」

// 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; 
} 
+2

您的代碼甚至不進行編譯。你的'getNumPicturesTakenIn'方法是什麼樣的? – Orin

+2

我懷疑這甚至會編譯。請閱讀以下內容:https://docs.oracle.com/javase/tutorial/essential/regex/ – Taylor

+1

您的\ d是外部字符串。嘗試「\\ d /」+年 – talex

回答

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