简体   繁体   中英

NSDataDetector to detect a name in a string

I have been struggling to understand the NSDataDetector class for a little while now. I've read the documentation and just can't grasp it. Everything I do Xcode tells me there is an error.

I feel like I might be on the right path with this attempt. How can I write a simple foundation program to find name in a string?

 NSError *error = nil;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress error:&error];
    NSString *string = @"(555) 555-5555 / Nick";
    NSArray *matches = [detector matchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];

    for (NSTextCheckingResult *match in matches) {
        if([match addressComponents] // contains NSTextCheckingNameKey){
            // do this
        }
    }

Your code uses a data detector that looks for an address. There is no address in your string. Therefore the data detector can't find anything.

There is no data detector for finding a name.

If you know the structure of the string, then use it. For example, if you can guarantee that there will always be "space-slash-space" before the name as in your example, then search for that and take what follows to be a name.

If you do not know the structure of the string, the problem is pretty much unsolvable.

NSDataDetector does not support name detection. Use NSLinguisticTagger for this instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM