简体   繁体   English

NSDataDetector检测字符串中的名称

[英]NSDataDetector to detect a name in a string

I have been struggling to understand the NSDataDetector class for a little while now. 我一直在努力理解NSDataDetector类。 I've read the documentation and just can't grasp it. 我已经阅读了文档,但无法理解。 Everything I do Xcode tells me there is an error. 我所做的一切Xcode都告诉我有一个错误。

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. 例如,如果您可以像示例中那样保证名称前始终有“ space-slash-space”,那么请搜索该名称,然后将其作为名称。

If you do not know the structure of the string, the problem is pretty much unsolvable. 如果您知道字符串的结构,则该问题几乎无法解决。

NSDataDetector does not support name detection. NSDataDetector不支持名称检测。 Use NSLinguisticTagger for this instead. 为此 ,请使用NSLinguisticTagger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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