2017-01-08 52 views
0

在字符串中,我存儲了HTML文件的原始內容。在這個文件如下:如何從字符串中刪除某個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> 

有一個簡單的操作來做到這一點?或者將整個文件標記爲更好?

+0

我以前用這個庫在swift上解析html,https://github.com/tid-kijyun/Kanna – Sri

回答

0

您可以使用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。

+0

剛注意到也會刪除空的div,可能要調整一下。 –

相關問題