我写了一个小应用程序来从字符串中截取正确的日期。当我有一个字符串时,可以说“2007-01-12sth”它可以正常工作,它会打印“2007-01-12”。当我有一个字符串“txt2008-01-03”时就不行了......我认为解释这个的最好方法是粘贴我的整个代码:
public class test
{
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
try {
df.parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
public static void main(String[] args) {
// txt2008-01-03 is NOT ok INCORRECT, should print 2008-01-03
// 2007-01-12sth is ok CORRECT
// 20999-11-11 is is NOT ok CORRECT
String date = "txt2008-01-03";
Pattern p = Pattern.compile("\\d{4}-[01]\\d-[0-3]\\d");
Matcher m = p.matcher(date);
if(m.find())
date = date.substring(0, m.end());
if(isValid(date))
System.out.println(date + " ");
}
}
如何从“txt2008-01-03”和“2007-01-12sth”中删除日期?(不仅来自“2007-01-12”)