문자열에서 올바른 날짜를 잘라내는 작은 응용 프로그램을 작성했습니다. 문자열이있을 때 "2007-01-12sth"라고 말하면 "2007-01-12"가 인쇄됩니다.문자열에서 날짜 잘라 내기
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에서 날짜를 줄일 수 방법 : 나는 문자열"txt2008-01-03 "이 때의하지 확인 ... 나는 이것을 설명하는 가장 좋은 방법이 붙여 내 전체 코드라고 생각합니다 -01-03 "AND"2007-01-12sth "? 매처 찾았는지
if(m.find())
date = date.substring(0, m.end());
그냥 잡아 :
if (m.find())
date = m.group();
그러나이있다 (뿐만 아니라 "2007-01-12sth"에서)
+1. 'm.group()'이 최선의 해결책입니다. 그는 또한'0'을'm.start()'로 대체 할 수있었습니다. – jlordo