如何使用 html 标签从 NSString 中过滤数字?
How to filter a number from NSString with html tags?
我有一个带有 html 标签的以下 NSString。我只想要字符串中的电话号码。
<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>
有人可以帮我解决这个问题吗?
提前致谢。
这并不容易,因为数据嵌入在一个复杂的结构中。格式的简单更改会广泛影响您的代码。简单地想想正文中包含格式为 "tel:12345" 的字符串的情况......
最可靠的处理方法是使用 html-解析器。
你从哪里得到字符串?
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);
}
希望对您有所帮助!
我有一个带有 html 标签的以下 NSString。我只想要字符串中的电话号码。
<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>
有人可以帮我解决这个问题吗? 提前致谢。
这并不容易,因为数据嵌入在一个复杂的结构中。格式的简单更改会广泛影响您的代码。简单地想想正文中包含格式为 "tel:12345" 的字符串的情况......
最可靠的处理方法是使用 html-解析器。
你从哪里得到字符串?
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);
}
希望对您有所帮助!