Search code examples
htmliosobjective-cnsstringnsattributedstring

How to filter a number from NSString with html tags?


I have a following NSString with html tags. I want the telephone number alone from the string.

<div><a href="tel:12345" x-apple-data-detectors="true" x-apple-data-detectors-type="telephone" x-apple-data-detectors-result="0">473737474747</a></div>

Can some one please help me out in this?. Thanks in advance.


Solution

  • NSString *str = @"<div><a href=\"tel:12345\" x-apple-data-detectors=\"true\" x-apple-data-detectors-type=\"telephone\" x-apple-data-detectors-result=\"0\">473737474747</a></div>";
    
    NSError *error;
    
    NSDataDetector *detector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypePhoneNumber error:&error];
    
    NSArray * matches = [detector matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    
    for(NSTextCheckingResult *match in matches)
    {
        NSString *phoneNumber = match.phoneNumber;
    
        NSLog(@"%@",phoneNumber);
    }
    

    hope it helps!