2014-11-15 2 views
3

내 앱이 날짜를 식별하도록하려고합니다. 검색 할 문자열 배열이 있습니다. rangeOfString()을 사용하여 날짜에있는 "/"을 검색합니다. 그러나 문자열의 일부 영역에는 날짜의 일부가 아닌 백 슬래시가 있으며 이는 검색을 엉망으로 만듭니다. 숫자 바로 뒤에 백 슬래시를 검색하도록 할 수 있습니까? PHP에서는 preg_match ("/// [0-9] /")가 될 것입니다. 그러나 Swift를 사용하면 어떻게됩니까?임의의 숫자에 대한 신속 검색 문자열?

+0

'NSRegularExpression'을 찾으셨습니까? – Larme

+0

무엇이며 어떻게 사용할 수 있습니까? – user3142972

+0

https://developer.apple.com/LIBRARY/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html – Larme

답변

3

당신이 당신의 문자열에 어떤 날짜와 일치해야하는 경우가 NSDataDetector 사용할 수 있습니다 - 일부 특정 데이터를 감지하도록 설계 NSRegularExpression 서브 클래스 :

스위프트 버전 :

var error : NSError? 

if let detector = NSDataDetector(types: NSTextCheckingType.Date.rawValue, error: &error) { 
    let testString = "Today date is 15/11/2014!! Yesterday was 15-11-2014" 

    let matches = detector.matchesInString(testString, options: .allZeros, range: NSMakeRange(0, countElements(testString))) as [NSTextCheckingResult] 

    for match:NSTextCheckingResult in matches { 
    println(match.date, match.range) 
    } 
} 

의 Obj-C 버전 :

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate 
                  error:NULL]; 
NSString* testString = @"Today date is 15/11/2014!! Yesterday was 14-11-2014"; 
NSArray* matches = [detector matchesInString:testString 
            options:0 
             range:NSMakeRange(0, testString.length)]; 
// Will match 2 date occurences 
for (NSTextCheckingResult* match in matches) { 
    NSLog(@"%@ in %@", match.date, NSStringFromRange(match.range)); 
} 
+0

죄송합니다. 신속한 답변을 놓치 셨습니다. 신속한 샘플 코드를 답변에 추가했습니다. – Vladimir