swift中的正則表達(dá)式小結(jié)
作為一門先進(jìn)的編程語言,Swift 可以說吸收了眾多其他先進(jìn)語言的優(yōu)點(diǎn),但是有一點(diǎn)卻是讓人略微失望的,就是 Swift 至今為止并沒有在語言層面上支持正則表達(dá)式。
正則表達(dá)式的用處:
判斷給定的字符串是否符合某一種規(guī)則(專門用于操作字符串)
- 電話號(hào)碼,電子郵箱,URL...
- 可以直接百度別人寫好的正則
- 別人真的寫好了,而且測(cè)試過了,我們可以直接用
- 要寫出沒有漏洞正則判斷,需要大量的測(cè)試,通常最終結(jié)果非常負(fù)責(zé)
過濾篩選字符串,網(wǎng)絡(luò)爬蟲
替換文字,QQ聊天,圖文混排
語法規(guī)則
使用過程
1、創(chuàng)建規(guī)則
2、創(chuàng)建正則表達(dá)式對(duì)象
3、開始匹配
代碼示例
private func check(str: String) { // 使用正則表達(dá)式一定要加try語句 do { // - 1、創(chuàng)建規(guī)則 let pattern = "[1-9][0-9]{4,14}" // - 2、創(chuàng)建正則表達(dá)式對(duì)象 let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) // - 3、開始匹配 let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)) // 輸出結(jié)果 for checkingRes in res { print((str as NSString).substringWithRange(checkingRes.range)) } } catch { print(error) } }
其他幾個(gè)常用方法
// 匹配字符串中所有的符合規(guī)則的字符串, 返回匹配到的NSTextCheckingResult數(shù)組 public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult] // 按照規(guī)則匹配字符串, 返回匹配到的個(gè)數(shù) public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int // 按照規(guī)則匹配字符串, 返回第一個(gè)匹配到的字符串的NSTextCheckingResult public func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult? // 按照規(guī)則匹配字符串, 返回第一個(gè)匹配到的字符串的范圍 public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange
使用子類來匹配日期、地址、和URL
看官網(wǎng)文檔解釋,可以知道這個(gè) NSDataDetector 主要用來匹配日期、地址、和URL。在使用時(shí)指定要匹配的類型
public class NSDataDetector : NSRegularExpression { // all instance variables are private /* NSDataDetector is a specialized subclass of NSRegularExpression. Instead of finding matches to regular expression patterns, it 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 NSTextCheckingResult instances returned will be of the appropriate types from that list. */ public init(types checkingTypes: NSTextCheckingTypes) throws public var checkingTypes: NSTextCheckingTypes { get } } // 這個(gè)是類型選擇 public static var Date: NSTextCheckingType { get } // date/time detection public static var Address: NSTextCheckingType { get } // address detection public static var Link: NSTextCheckingType { get } // link detection
NSDataDetector 獲取URL示例
/** 匹配字符串中的URLS - parameter str: 要匹配的字符串 */ private func getUrl(str:String) { // 創(chuàng)建一個(gè)正則表達(dá)式對(duì)象 do { let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue)) // 匹配字符串,返回結(jié)果集 let res = dataDetector.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)) // 取出結(jié)果 for checkingRes in res { print((str as NSString).substringWithRange(checkingRes.range)) } } catch { print(error) } }
".*?" 可以滿足一些基本的匹配要求
如果想同時(shí)匹配多個(gè)規(guī)則 ,可以通過 "|" 將多個(gè)規(guī)則連接起來
將字符串中文字替換為表情
/** 顯示字符中的表情 - parameter str: 匹配字符串 */ private func getEmoji(str:String) { let strM = NSMutableAttributedString(string: str) do { let pattern = "\\[.*?\\]" let regex = try NSRegularExpression(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[--count] let tempStr = (str as NSString).substringWithRange(checkingRes.range) // 轉(zhuǎn)換字符串到表情 if let emoticon = EmoticonPackage.emoticonWithStr(tempStr) { print(emoticon.chs) let attrStr = EmoticonTextAttachment.imageText(emoticon, font: 18) strM.replaceCharactersInRange(checkingRes.range, withAttributedString: attrStr) } } print(strM) // 替換字符串,顯示到label emoticonLabel.attributedText = strM } catch { print(error) } }
TextKit 給URL高亮顯示
主要用到三個(gè)類
NSTextStorage
NSLayoutManager
NSTextContainer
自定義UILabel來實(shí)現(xiàn)url高亮
1、定義要用到的屬性
/* 只要textStorage中的內(nèi)容發(fā)生變化, 就可以通知layoutManager重新布局 layoutManager重新布局需要知道繪制到什么地方, 所以layoutManager就會(huì)文textContainer繪制的區(qū)域 */ // 準(zhǔn)們用于存儲(chǔ)內(nèi)容的 // textStorage 中有 layoutManager private lazy var textStorage = NSTextStorage() // 專門用于管理布局 // layoutManager 中有 textContainer private lazy var layoutManager = NSLayoutManager() // 專門用于指定繪制的區(qū)域 private lazy var textContainer = NSTextContainer() override init(frame: CGRect) { super.init(frame: frame) setupSystem() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSystem() } private func setupSystem() { // 1.將layoutManager添加到textStorage textStorage.addLayoutManager(layoutManager) // 2.將textContainer添加到layoutManager layoutManager.addTextContainer(textContainer) } override func layoutSubviews() { super.layoutSubviews() // 3.指定區(qū)域 textContainer.size = bounds.size }
2、重寫label的text屬性
override var text: String? { didSet{ // 1.修改textStorage存儲(chǔ)的內(nèi)容 textStorage.setAttributedString(NSAttributedString(string: text!)) // 2.設(shè)置textStorage的屬性 textStorage.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSMakeRange(0, text!.characters.count)) // 3.處理URL self.URLRegex() // 2.通知layoutManager重新布局 setNeedsDisplay() } }
3、匹配字符串
func URLRegex() { // 1.創(chuàng)建一個(gè)正則表達(dá)式對(duì)象 do{ let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue)) let res = dataDetector.matchesInString(textStorage.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, textStorage.string.characters.count)) // 4取出結(jié)果 for checkingRes in res { let str = (textStorage.string as NSString).substringWithRange(checkingRes.range) let tempStr = NSMutableAttributedString(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) } }catch { print(error) } }
4、重繪文字
// 如果是UILabel調(diào)用setNeedsDisplay方法, 系統(tǒng)會(huì)促發(fā)drawTextInRect override func drawTextInRect(rect: CGRect) { // 重繪 // 字形 : 理解為一個(gè)小的UIView /* 第一個(gè)參數(shù): 指定繪制的范圍 第二個(gè)參數(shù): 指定從什么位置開始繪制 */ layoutManager.drawGlyphsForGlyphRange(NSMakeRange(0, text!.characters.count), atPoint: CGPointZero) }
獲取label中URL的點(diǎn)擊
如果要獲取URL的點(diǎn)擊,那么必須獲取點(diǎn)擊的范圍
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // 1、獲取手指點(diǎn)擊的位置 let touch = (touches as NSSet).anyObject()! let point = touch.locationInView(touch.view) print(point) // 2、獲取URL區(qū)域 // 注意: 沒有辦法直接設(shè)置UITextRange的范圍 let range = NSMakeRange(10, 20) // 只要設(shè)置selectedRange, 那么就相當(dāng)于設(shè)置了selectedTextRange selectedRange = range // 給定指定的range, 返回range對(duì)應(yīng)的字符串的rect // 返回?cái)?shù)組的原因是因?yàn)槲淖挚赡軗Q行 let array = selectionRectsForRange(selectedTextRange!) for selectionRect in array { if CGRectContainsPoint(selectionRect.rect, point) { print("點(diǎn)擊了URL") } } }
以上內(nèi)容就是小編跟大家介紹的swift中的正則表達(dá)式小結(jié),希望大家喜歡。
相關(guān)文章
正則表達(dá)式在javascript中的幾個(gè)實(shí)例
正則表達(dá)式在javascript中的幾個(gè)實(shí)例...2006-06-06史上最全的PHP正則表達(dá)式(手機(jī)號(hào)需要加上177-***)
正則表達(dá)式,大家在開發(fā)中應(yīng)該是經(jīng)常用到,現(xiàn)在很多開發(fā)語言都有正則表達(dá)式的應(yīng)用,比如javascript,java,.net,php等等,今天給大家介紹史上最全的PHP正則表達(dá)式(手機(jī)號(hào)需要加上177-***),一起看看吧2017-10-10基于正則表達(dá)式實(shí)現(xiàn)UL下LI的樣式替換功能
這篇文章主要介紹了基于正則表達(dá)式實(shí)現(xiàn)UL下LI的樣式替換功能,涉及javascript使用正則表達(dá)式進(jìn)行頁面元素屬性動(dòng)態(tài)操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-05-05JS正則表達(dá)式獲取指定字符之后指定字符之前的字符串(推薦)
這篇文章主要介紹了JS正則表達(dá)式獲取指定字符之后指定字符之前的字符串,內(nèi)容比較簡(jiǎn)單,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-11-11如何使用JavaScript和正則表達(dá)式進(jìn)行數(shù)據(jù)驗(yàn)證
利用客戶端JavaScript的優(yōu)勢(shì),JavaScript中的正則表達(dá)式可以簡(jiǎn)化數(shù)據(jù)驗(yàn)證的工作,下面與大家分享下如何使用JavaScript和正則表達(dá)式進(jìn)行數(shù)據(jù)驗(yàn)證,感興趣的朋友可以參考下哈2013-05-05最新手機(jī)號(hào)碼、電話號(hào)碼正則表達(dá)式
相信大家對(duì)正則表達(dá)式一定都有所了解和研究,這篇文章主要為大家分享了最新驗(yàn)證手機(jī)號(hào)碼和電話號(hào)碼的正則表達(dá)式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11最常用的15個(gè)前端表單驗(yàn)證JS正則表達(dá)式
在表單驗(yàn)證中,使用正則表達(dá)式來驗(yàn)證正確與否是一個(gè)很頻繁的操作,本文收集整理了15個(gè)常用的JavaScript正則表達(dá)式,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-07-07