6

我一直在使用NSDataDetector从字符串中解析地址,并且在大多数情况下它做得很好。但是,在与此类似的地址上,它不会检测到它。

6200 North Evan Blvd Suit 487 Highland UT 84043

目前我正在使用这段代码:

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];

    }
}

任何人都可以建议一种更强大的方法来解析字符串中的物理地址吗?我需要能够获得邮编、街道、州和城市。

4

2 回答 2

2

ANSDataDetector是一个NSRegularExpression子类,所以也许您可以创建一个自定义实例并首先检查 Apple 放置的内容patternoptions参数。


沿着这条线的东西:

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];
于 2014-06-04T02:21:37.263 回答
1

您可以尝试使用正则表达式(RegEx)解析地址信息,我认为这是更稳健的方式。请参阅以下参考以使用 RegEx:使 RegEx 在 Objective-C 中变得简单,Objective-C RegEx 类别可在GitHub 上获得。

于 2014-06-02T00:22:47.363 回答