翻譯NSHipster,NSRegular?Expression 正則表達(dá)式(全)

有些人說(shuō): 遇到問(wèn)題,明白了。我要用 NSRegular?Expression:? 正則表達(dá)式, 現(xiàn)在有三個(gè)問(wèn)題

編程世界里, 正則表達(dá)式應(yīng)用廣泛。 有些覺(jué)得這個(gè)十分難以理解, 符號(hào)密集。 更多的程序員覺(jué)得,正則表達(dá)式是代碼的基礎(chǔ) ,是一個(gè)笑話。

有些程序員覺(jué)得,正則表達(dá)式,真是輕便,有強(qiáng)大。沒(méi)有工具庫(kù)這樣通用的神器的人,不知道他們?cè)趺垂ぷ鞯摹?/p>

首先,我們都認(rèn)為,Cocoa 在NSRegularExpression中,封裝了你不曾見(jiàn)識(shí)過(guò)的 強(qiáng)大的正則表達(dá)式。

不行嗎?我們從這個(gè)HTML片段中提取鏈接,先用Ruby



htmlSource = "Questions? Corrections??[@NSHipster](http://www.itdecent.cn/%22https://twitter.com/NSHipster/%22)?or?[on GitHub](http://www.itdecent.cn/%22https://github.com/NSHipster/articles/%22)."?linkRegex = /]*href="([^"]*)"[^>]*>/ilinks = htmlSource.scan(linkRegex)puts(links)# https://twitter.com/NSHipster# https://github.com/NSHipster/articles



兩三行程序,看你怎么數(shù)了。還行吧,現(xiàn)在試試在Swift 中使用 NSRegularExpression 提取鏈接

let htmlSource="Questions? Corrections??[@NSHipster](http://www.itdecent.cn/%22https://twitter.com/NSHipster/%22)?or?[on GitHub](http://www.itdecent.cn/%22https://github.com/NSHipster/articles/%22)."let linkRegexPattern = "]*href=\"([^\"]*)\"[^>]*>"let linkRegex = try! NSRegularExpression(pattern: linkRegexPattern , options:.caseInsensitive) let matches = linkRegex.matches(in:htmlSource,range:NSMakeRange(0,htmlSource.utf16.count))let links = matches.map{result->Stringinglet hrefRange = result.rangeAt(1)let start = String.UTF16Index(hrefRange.location)let end = String.UTF16Index(hrefRange.location+hrefRange.length)return String(htmlSource.utf16[start..String? { guard let range = nsrange.toRange() else { return nil } let start = UTF16Index(range.lowerBound) let end = UTF16Index(range.upperBound) return String(utf16[start..Range? { guard let range = nsrange.toRange() else { return nil } let utf16Start = UTF16Index(range.lowerBound) let utf16End = UTF16Index(range.upperBound) guard let start = Index(utf16Start, within: self), let end = Index(utf16End, within: self) else { return nil } return start..

1 NSTextCheckingResult的實(shí)例 ? ,

2 這些代碼, 我都沒(méi)碼一下的 ?>

3 [四種不同的編碼方式](https://developer.apple.com/swift/blog/?id=30) ///?

4 返回與 給定范圍相同的范圍?

// 如果該范圍,轉(zhuǎn)換失敗,返回nil func range(from nsrange: NSRange) -> Range? {








參考資料:

NSHipster 的Regex 原文

好用的學(xué)習(xí)正則的github repo


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容