2013-06-27 7 views
-1

검색된 파일 이름 (문자열) 중에서 매우 이상한 형식으로 저장된 날짜 및 시간 문자열을 추출하는 최선의 방법을 찾으려고합니다. FTP 파일 목록에서. 다음과 같이문자열에서 복잡한 날짜/시간 형식 추출 중

문자열은 다음과 같습니다

-rwxr-xr-x 1 ftp  ftp  267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r 

I 추출하려고 특정 데이터 20130606_021303입니다. 021303은 시간, 초 및 밀리 초로 포맷됩니다. DateTime.Parse 및 DateTime.ParseExact는 협조 할 의사가 없습니다. 이걸 어떻게 실행시켜야하는지에 대한 아이디어가 있습니까?

답변

1

UPDATE 나는 FTP 목록의 파일 표시에 고정 된 구조가 있다고 가정, 그래서 당신은 단순히 날짜 문자열을 추출하는 String.Substring를 사용하고 DateTime.ParseExact으로 분석 할 수 :

var s = "-rwxr-xr-x 1 ftp  ftp  267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r"; 
var datetime = DateTime.ParseExact(s.Substring(72,15),"yyyyMMddHHmmss",null); 


Original 응답

정규식을 사용하십시오. ParseExact를 사용

var s = "-rwxr-xr-x 1 ftp  ftp  267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r"; 

/* 
    The following pattern means: 
    \d{8}) 8 digits (\d), captured in a group (the parentheses) for later reference 
    _   an underscore 
    (\d{6}) 6 digits in a group 
    \.   a period. The backslash is needed because . has special meaning in regular expressions 
    .*   any character (.), any number of times (*) 
    \r   carriage return 
    $   the end of the string 
*/ 
var pattern = @"(\d{8})_(\d{6})\..*\r$"; 

var match = Regex.Match(s, pattern); 
string dateString = matches.Groups[1].Value; 
string timeString = matches.Groups[2].Value; 

및 분석 : 다음을 시도

var datetime = DateTime.ParseExact(dateString + timeString,"yyyyMMddHHmmss",null); 
3

이 보이는 사용 권한, 사용자, 소유자, 파일 크기, 타임 스탬프와 파일 이름을 포함하여 파일 목록의 전체 행을 가지고 같은 .

요청하는 데이터는 파일 이름의 일부일뿐입니다. 먼저 기본 문자열 조작 (Split, Substring 등 ...)을 사용하십시오. 그런 다음 datetime 부분 만 있으면 DateTime.ParseExact을 호출 할 수 있습니다.

먼저 시도해보십시오. 문제가 생기면 질문을 업데이트하여 시도하는 코드를 표시하면 다른 사람이 더 도움이 될 것입니다.

...

오, 괜찮습니다. 이런 젠장. 나는 기분이 좋아. 한 줄짜리예요.

string s = // your string as in the question 

DateTime dt = DateTime.ParseExact(string.Join(" ", s.Split('_', '.'), 1, 2), 
            "yyyyMMdd HHmmss", null); 

하지만 다음에 처음부터 시도해보십시오.

+0

내가 ParseExact''에'null'를 전달하는 생각하지 않았다. –

+1

@ZevSpitz - 공급자에 대해 'null'을 전달하면 현재 culture를 사용하도록 지시합니다. 대신에'CultureInfo.InvariantCulture'를 전달할 수 있습니다. 이 특정 형식 문자열에는 문화 관련 항목이 없기 때문에 여기서는 중요하지 않습니다. –

0

이 작동 할 수 있습니다 :

string s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r"; 

// you might need to adjust the IndexOf method a bit - if the filename/string ever changes... 
// or use a regex to check if there's a date in the given string 

// however - the first thing to do is extract the dateTimeString: 
string dateTimeString = s.Substring(s.IndexOf("_") + 1, 15); 

// and now extract the DateTime (you could also use DateTime.TryParseExact) 
// this should save you the trouble of substringing and parsing loads of ints manually :) 
DateTime dt = DateTime.ParseExact(dateTimeString, "yyyyMMdd_hhmmss", null);