Analysis address from NSString without NSDataDetector

I used NSDataDetector to parse addresses from strings and, for the most part, it does a good job. However, at an address like this, he does not detect it.

6200 North Evan Blvd Suit 487 Highland UT 84043

I am currently using this code:

 NSError *error = nil; NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress error:&error]; NSArray *matches = [detector matchesInString:output options:0 range:NSMakeRange(0, [output length])]; for (NSTextCheckingResult *match in matches) { if ([match resultType] == NSTextCheckingTypeAddress) { _address = [_tesseractData substringWithRange:[match range]]; NSDictionary *data = [match addressComponents]; _zip = [data objectForKey:@"ZIP"]; if (_zip) { NSRange zipRange = [_tesseractData rangeOfString:_zip]; if (zipRange.location != NSNotFound) { [_tesseractData deleteCharactersInRange:zipRange]; } } _city = [data objectForKey:@"City"]; if (_city) { NSRange cityRange = [_tesseractData rangeOfString:[_city uppercaseString]]; if (cityRange.location != NSNotFound) { [_tesseractData deleteCharactersInRange:cityRange]; } } _city = [_city capitalizedString]; _state = [data objectForKey:@"State"]; _street = [data objectForKey:@"Street"]; if (_street) { NSRange streetRange = [_tesseractData rangeOfString:[_street uppercaseString]]; if (streetRange.location != NSNotFound) { [_tesseractData deleteCharactersInRange:streetRange]; } } _street = [_street capitalizedString]; } } 

Can anyone suggest a more reliable method for parsing a physical address from a string? I need to get Zip, Street, State and City.

+6
source share
2 answers

A NSDataDetector is a subclass of NSRegularExpression , so maybe you can create a custom instance and start by checking what Apple sets as pattern and options .


Something like that:

 NSDataDetector * dataDetectorRegEx = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress error:&error]; NSString * dataDetectorPattern = dataDetectorRegEx.pattern; NSLog(@"Check out this pattern!: %@", dataDetectorPattern); // Customize the pattern for your special cases NSString * customPattern = [NSString stringWithFormat:@"<MY_OTHER_PATERNS + %@>", dataDetectorPattern]; NSRegularExpression * customDataDetectorLikeRegEx = [NSRegularExpression regularExpressionWithPattern:customPattern options:someOptions error:&error]; 
+2
source

You can try to parse the address information using regular expressions (RegEx), I think this is a more reliable way. See the following link for working with RegEx: Creating RegEx Easy in Objective-C , Objective-C RegEx categories are available on GitHub .

+1
source

Source: https://habr.com/ru/post/970018/


All Articles