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