2016-09-22 11 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(); 
    } 
}