【问题标题】:How to filter a number from NSString with html tags?如何使用 html 标签从 NSString 中过滤数字?
【发布时间】:2015-04-09 13:02:00
【问题描述】:

我有一个带有 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>

有人可以帮我解决这个问题吗? 提前致谢。

【问题讨论】:

  • 我猜 NSScanner 可能对你有帮助。

标签: html ios objective-c nsstring nsattributedstring


【解决方案1】:
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);
}

希望对你有帮助!

【讨论】:

  • +1 为这个好主意。但是 AFAIK 是一个数据检测器,用于识别直接“人类可读”文档中的数据。不知道,它是否在 html 标签上正常工作。
  • 谢谢,数据检测器通常适用于任何字符串,无论是人类可读的还是 html 或其他任何字符串,BTY 您可以检测 Web 链接和其他一些很酷的东西,请检查 NSTextCheckingTypes 枚举以获取完整列表。
【解决方案2】:

这并不容易,因为数据嵌入在一个复杂的结构中。格式的简单更改可以广泛影响您的代码。简单想想body也包含格式为“tel:12345”的字符串的情况……

最可靠的处理方法是使用 html 解析器。

你从哪里得到字符串?

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2020-08-23
    • 2014-07-08
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2012-12-29
    • 2023-04-11
    相关资源
    最近更新 更多