2013-06-09 5 views
1

문자열에서 올바른 날짜를 잘라내는 작은 응용 프로그램을 작성했습니다. 문자열이있을 때 "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"에서)

답변

4

귀하의 문제는 당신이 날짜를 잡아 방법입니다 여전히 문제 : 20999-11-11으로 정규 표현식은 0999-11-11을 추출합니다 (어쩌면이 코드를 고려하여 초기 코드가 작성 되었습니까?). 이 당신의 정규식 교체 : "전에 ... 일치하지 않는 어떤 위치를 찾을 수 있습니다"

// A date, as long as it is NOT preceded/followed by a digit 
Pattern p = Pattern.compile("(?<!\\d)\\d{4}-[01]\\d-[0-3]\\d(?!\\d)"); 

(?<!...)가 부정적인 lookbehind이다.

(?!...)은 "다음에 오는 위치가 일치하지 않는 위치를 찾으십시오. ..."입니다.

긍정적 인 버전 : (?<=...), (?=...).

+0

+1. 'm.group()'이 최선의 해결책입니다. 그는 또한'0'을'm.start()'로 대체 할 수있었습니다. – jlordo