【问题标题】:NSDataDetector phone numbersNSDataDetector 电话号码
【发布时间】:2026-01-09 06:00:01
【问题描述】:

我正在使用 NSDataDetector 解析文本并检索数字。这是我的代码:

 NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
 error:&error];

NSArray *matches = [detector matchesInString:locationAndTitle options:0 range:NSMakeRange(0,[locationAndTitle length])];

for (NSTextCheckingResult *match in matches) {


        if ([match resultType] == NSTextCheckingTypePhoneNumber) {

            self.theNumber = [match phoneNumber];
        }
    }

问题在于它有时会返回如下内容:

电话:9729957777 或者 9729957777x3547634

我不希望它出现并且删除它会更难然后使用正则表达式代码来检索数字。您对如何仅检索号码有任何想法吗?

【问题讨论】:

    标签: ios regex phone-number


    【解决方案1】:

    我个人只会在字符串上使用-substringWithRange: 来删除过去的所有内容,包括“x”字符:

    NSString * myPhoneNum = @"9729957777x3547634";
    NSRange r = [myPhoneNum rangeOfString:@"x"];
    if (r.location != NSNotFound) {
        myPhoneNum = [myPhoneNum substringWithRange:NSMakeRange(0, r.location)];
    }
    NSLog(@"Fixed number: %@", myPhoneNum);
    

    知道 x3547634 是从哪里来的吗?

    【讨论】:

      最近更新 更多