简体   繁体   中英

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.

This is not done easily, because the data is embedded in a complex structure. Simple changes in the format can influence your code widely. Simply think of the case that the body contains a string of the format "tel:12345", too …

The most robust way to handle that is to use a html-parser.

From where do you get the string?

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!

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