A quick search string for any number?
I am trying to find my application for determining dates. I have an array of strings that it is looking at. I am using rangeOfString () to search for "/" that is in dates. However, some areas in strings have backslashes that are not part of the dates, and this interferes with the search. Can I make it look for the backslash immediately after the number. In PHP this would be preg_match ("/// [0-9] /"), but how is it done with Swift?
+3
source to share
1 answer
If you need to match any date in your string, you can use the NSDataDetector subclass - NSRegularExpression, designed to discover some specific data:
Swift version:
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 version:
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));
}
+3
source to share