ios - 如何从字符串中删除特定的 html 片段

标签 ios swift string

在字符串中,我存储 HTML 文件的原始内容。该文件的内容如下:

<div class="input-wrapper">
        <input type="search" name="search" placeholder="page" title="Page" accesskey="f" id="searchInput" class="search" autocomplete="off" readonly="">
</div>

我想删除这个以及这个:

<div><a title="Open main menu" href="/wiki/Special:MobileMenu" class="mw-ui-icon mw-ui-icon-element mw-ui-icon-mainmenu main-menu-button" id="mw-mf-main-menu-button">Open main menu</a></div>

有没有简单的操作可以做到这一点?或者标记整个文件会更好吗?

最佳答案

您可以使用 Sri 建议的 HTML 解析器库,如果您要进一步操作 HTML 或者您不能保证 HTML 将来不会更改,我建议您使用该库。不过,如果您只是删除特定的 HTML,那么您可以使用正则表达式作为更简单的替代方案。

do 
{
    let html = "<html> ... </html>"
    let regex:NSRegularExpression  = try NSRegularExpression(pattern: "<div\\s*(?:class=\"input-wrapper\")?>\\s*(?:<input type=\"search\" name=\"search\" placeholder=\"page\" title=\"Page\" accesskey=\"f\" id=\"searchInput\" class=\"search\" autocomplete=\"off\" readonly=\"\">)?(?:<a title=\"Open main menu\" href=\"\\/wiki\\/Special:MobileMenu\" class=\"mw\\-ui\\-icon mw\\-ui\\-icon\\-element mw\\-ui\\-icon\\-mainmenu main\\-menu\\-button\" id=\"mw\\-mf\\-main\\-menu\\-button\">Open main menu<\\/a>)?\\s*<\\/div>", options: NSRegularExpression.Options.caseInsensitive)
    let range = NSMakeRange(0, html.characters.count)
    let htmlStripped:String = regex.stringByReplacingMatches(in: html, options: NSRegularExpression.MatchingOptions(), range:range , withTemplate: "")
} 
catch 
{
        // ...
}

尚未完全测试,Swift 3.0。

关于ios - 如何从字符串中删除特定的 html 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535745/

相关文章:

c# - 不区分大小写比较字符串和非字符串

ios - 通用链接在 Safari 浏览器顶部显示横幅

ios - Swift 2.3,如何向Instabug报错?

ios - 如何隐藏 Xcode 6 中的按钮?

c++ - libc++ 中的短字符串优化机制是什么?

C 基本字符串问题

ios - iOS 应用程序的内存泄漏是否会利用任何漏洞?

ios - 如何在 SwiftUI 中为列表创建按字母顺序排列的部分索引?

ios - 我希望能够按照标签指定的顺序编辑文本字段。研究了很多都无济于事。我有点菜鸟

swift - 可以通过结构扩展 Swift 字典吗?