文件daty.txt
包含各种日期,其中一些是正确的,其他日期不是。我目前的模式看起来像\\d{4}-\\d{2}-\\d{2}
。很遗憾,这与20999-11-11
和2009-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;
}
}
答案 0 :(得分:1)
你可以使用负面的lookbehind和lookahead来说“只有在没有数字前面才匹配”和“只有在没有数字后才匹配”:
"(?<!\\d)\\d{4}-\\d{2}-\\d{2}(?!\\d)"
此处(?<!\d)
表示“不以数字开头”,(?!\d)
表示“未跟随数字”。
答案 1 :(得分:0)