与20999-11-11和2009-01-111等无效日期不匹配的模式

时间:2015-04-13 21:31:41

标签: java regex date

文件daty.txt包含各种日期,其中一些是正确的,其他日期不是。我目前的模式看起来像\\d{4}-\\d{2}-\\d{2}。很遗憾,这与20999-11-112009-01-111等无效日期相匹配。

我需要一个匹配有效日期的模式,而不是与无效日期匹配。

public class Main {

    public static void main(String[] args) {
        String fname = System.getProperty("user.home") + "/daty.txt";
        List<String> list = Dates(fname,"\\d{4}-\\d{2}-\\d{2}");
        System.out.println(list.toString());
    }

    public static List<String> Dates(String file, String pattern) {
        List<String> result = new ArrayList();
        Pattern p = Pattern.compile(pattern);
        try {
            Scanner scan = new Scanner(new File(file));
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                Matcher m = p.matcher(line);
                while (m.find()) {
                    String date = m.group();
                    try {
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        df.setLenient(false);
                        df.parse(date);
                        result.add(date);
                    } catch (Exception ex) {
                        System.out.println(ex.getMessage());
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return result;
    }
}

2 个答案:

答案 0 :(得分:1)

你可以使用负面的lookbehind和lookahead来说“只有在没有数字前面才匹配”和“只有在没有数字后才匹配”:

"(?<!\\d)\\d{4}-\\d{2}-\\d{2}(?!\\d)"

此处(?<!\d)表示“不以数字开头”,(?!\d)表示“未跟随数字”。

更详细的解释:http://www.regular-expressions.info/lookaround.html

答案 1 :(得分:0)

您还可以使用字边界:

\\b\\d{4}-\\d{2}-\\d{2}\\b

请参阅http://www.regular-expressions.info/wordboundaries.html