




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、swift中的正則表達式小結swift中的正則表達式小結正則表達式是對字符串操作的一種邏輯公式,用事先定義好的一些特定字符、及這些特定字符的組合,組成一個"規則字符串",這個"規則字符串"用來表達對字符串的一種過濾邏輯。作為一門先進的編程語言,Swift 可以說吸收了眾多其他先進語言的優點,但是有一點卻是讓人略微失望的,就是 Swift 至今為止并沒有在語言層面上支持正則表達式。正則表達式的用處:判斷給定的字符串是否符合某一種規則(專門用于操作字符串)- 電話號碼,電子郵箱,URL.- 可以直接百度別人寫好的正則- 別人真的寫好了,而且測試過了,我們可以
2、直接用- 要寫出沒有漏洞正則判斷,需要大量的測試,通常最終結果非常負責過濾篩選字符串,網絡爬蟲替換文字,QQ聊天,圖文混排語法規則使用過程1、創建規則2、創建正則表達式對象3、開始匹配代碼示例?123456789101112131415161718private func check(str: String) / 使用正則表達式一定要加try語句do / - 1、創建規則let pattern = "1-90-94,14"/ - 2、創建正則表達式對象let regex = try NSRegularExpression(pattern: pattern, options:
3、 NSRegularExpressionOptions.CaseInsensitive)/ - 3、開始匹配let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)/ 輸出結果for checkingRes in res print(str as NSString).substringWithRange(checkingRes.range)catch print(error)其他幾個常用方法 ?12345678
4、910/ 匹配字符串中所有的符合規則的字符串, 返回匹配到的NSTextCheckingResult數組public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult / 按照規則匹配字符串, 返回匹配到的個數public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int/ 按照規則匹
5、配字符串, 返回第一個匹配到的字符串的NSTextCheckingResultpublic func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult?/ 按照規則匹配字符串, 返回第一個匹配到的字符串的范圍public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange使用子類
6、來匹配日期、地址、和URL看官網文檔解釋,可以知道這個 NSDataDetector 主要用來匹配日期、地址、和URL。在使用時指定要匹配的類型?1234567891011public class NSDataDetector : NSRegularExpression / all instance variables are private/* NSDataDetector is a specialized subclass of NSRegularExpression. Instead of finding matches to regular expression patterns, i
7、t matches items identified by Data Detectors, such as dates, addresses, and URLs. The checkingTypes argument should contain one or more of the types NSTextCheckingTypeDate, NSTextCheckingTypeAddress, NSTextCheckingTypeLink, NSTextCheckingTypePhoneNumber, and NSTextCheckingTypeTransitInformation. The
8、 NSTextCheckingResult instances returned will be of the appropriate types from that list.*/public init(types checkingTypes: NSTextCheckingTypes) throwspublic var checkingTypes: NSTextCheckingTypes get / 這個是類型選擇public static var Date: NSTextCheckingType get / date/time detectionpublic static var Addr
9、ess: NSTextCheckingType get / address detectionpublic static var Link: NSTextCheckingType get / link detectionNSDataDetector 獲取URL示例?1234567891011121314151617181920/*匹配字符串中的URLS- parameter str: 要匹配的字符串*/private func getUrl(str:String) / 創建一個正則表達式對象do let dataDetector = try NSDataDetector(types: NSTe
10、xtCheckingTypes(NSTextCheckingType.Link.rawValue)/ 匹配字符串,返回結果集let res = dataDetector.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)/ 取出結果for checkingRes in res print(str as NSString).substringWithRange(checkingRes.range)catch print(error)&qu
11、ot;.*?" 可以滿足一些基本的匹配要求如果想同時匹配多個規則 ,可以通過 "|" 將多個規則連接起來將字符串中文字替換為表情?12345678910111213141516171819202122232425/*顯示字符中的表情- parameter str: 匹配字符串*/private func getEmoji(str:String) let strM = NSMutableAttributedString(string: str)do let pattern = ".*?"let regex = try NSRegularExpre
12、ssion(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)var count = res.count/ 反向取出文字表情while count > 0 let checkingRes = res-countlet tempStr = (str as NSSt
13、ring).substringWithRange(checkingRes.range)/ 轉換字符串到表情if let emoticon = EmoticonPackage.emoticonWithStr(tempStr) print(emoticon.chs)let attrStr = EmoticonTextAttachment.imageText(emoticon, font: 18)strM.replaceCharactersInRange(checkingRes.range, withAttributedString: attrStr)print(strM)/ 替換字符串,顯示到la
14、belemoticonLabel.attributedText = strMcatch print(error)TextKit 給URL高亮顯示主要用到三個類NSTextStorage NSLayoutManager NSTextContainer自定義UILabel來實現url高亮1、定義要用到的屬性?1234567891011121314151617181920212223242526/*只要textStorage中的內容發生變化, 就可以通知layoutManager重新布局layoutManager重新布局需要知道繪制到什么地方, 所以layoutManager就會文textConta
15、iner繪制的區域*/ 準們用于存儲內容的/ textStorage 中有 layoutManagerprivate lazy var textStorage = NSTextStorage()/ 專門用于管理布局/ layoutManager 中有 textContainerprivate lazy var layoutManager = NSLayoutManager()/ 專門用于指定繪制的區域private lazy var textContainer = NSTextContainer()override init(frame: CGRect) super.init(frame: f
16、rame)setupSystem()required init?(coder aDecoder: NSCoder) super.init(coder: aDecoder)setupSystem()private func setupSystem()/ 1.將layoutManager添加到textStoragetextStorage.addLayoutManager(layoutManager)/ 2.將textContainer添加到layoutManagerlayoutManager.addTextContainer(textContainer)override func layoutSu
17、bviews() super.layoutSubviews()/ 3.指定區域textContainer.size = bounds.size2、重寫label的text屬性?12345678910111213override var text: String?didSet/ 1.修改textStorage存儲的內容textStorage.setAttributedString(NSAttributedString(string: text!)/ 2.設置textStorage的屬性textStorage.addAttribute(NSFontAttributeName, value: UIF
18、ont.systemFontOfSize(20), range: NSMakeRange(0, text!.characters.count)/ 3.處理URLself.URLRegex()/ 2.通知layoutManager重新布局setNeedsDisplay()3、匹配字符串?1234567891011121314151617181920func URLRegex()/ 1.創建一個正則表達式對象dolet dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawVa
19、lue)let res = dataDetector.matchesInString(textStorage.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, textStorage.string .characters.count)/ 4取出結果for checkingRes in reslet str = (textStorage.string as NSString).substringWithRange(checkingRes.range)let tempStr = NSMutableAttri
20、butedString(string: str)/ tempStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, str.characters.count)tempStr.addAttributes(NSFontAttributeName: UIFont.systemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor(), range: NSMakeRange(0, str.characters.count)textStorage.replaceCharactersInRange(checkingRes.range, withAttributedString: tempStr)catchprint(error)4、重繪文字?12345678910/ 如果是UILabel調用setNeedsDisplay方法, 系統會促發drawTextInRectoverride func drawTextInRect(rect: CGRect) / 重繪/ 字形 : 理解為一個小的UIView/*第一個參數: 指定繪制的范圍第二個參數: 指定從什么位置開始繪制*/
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年生物醫學工程專業實習考試試題及答案
- Rhodirubin-B-生命科學試劑-MCE
- 2025年市場營銷學期末考試試卷及答案
- D-L-Sulforaphane-glutathione-d5-DL-SFN-GSH-d-sub-5-sub-生命科學試劑-MCE
- 2025年農村基層干部培訓考試試題及答案
- 2025年交通運輸專業知識考試試題及答案
- 中秋節熱鬧之景作文11篇
- 少年中國說:文言文敘事手法與文化意義解析教案
- 小學生作文蒲公英的約定(5篇)
- 我懂得了珍惜友愛(10篇)
- 山東建筑大學《模擬電路與數字電路》2023-2024學年第二學期期末試卷
- 2025寫字樓租賃定金合同的范本
- 醫療行業變革下的職業轉型策略
- 2025年大數據分析師中級職稱考試試題集
- 裝修公司分公司合同協議
- 2025年全國低壓電工證理論考試練習題庫(含答案)
- 專題學習《2030年前碳達峰行動方案》課件全文
- 多元固廢水泥基膠凝材料性能研究
- 2025-2030建筑檢測行業市場發展現狀分析及競爭格局與投資價值研究報告
- 病毒性心肌炎病例分析與治療
- 鐵路旅客運輸服務站臺服務46課件
評論
0/150
提交評論