麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > Regex > 正文

swift中的正則表達(dá)式小結(jié)

2020-03-16 21:03:45
字體:
供稿:網(wǎng)友

正則表達(dá)式是對字符串操作的一種邏輯公式,用事先定義好的一些特定字符、及這些特定字符的組合,組成一個"規(guī)則字符串",這個"規(guī)則字符串"用來表達(dá)對字符串的一種過濾邏輯。

作為一門先進(jìn)的編程語言,Swift 可以說吸收了眾多其他先進(jìn)語言的優(yōu)點,但是有一點卻是讓人略微失望的,就是 Swift 至今為止并沒有在語言層面上支持正則表達(dá)式。

正則表達(dá)式的用處:

判斷給定的字符串是否符合某一種規(guī)則(專門用于操作字符串)

- 電話號碼,電子郵箱,URL...

- 可以直接百度別人寫好的正則

- 別人真的寫好了,而且測試過了,我們可以直接用

- 要寫出沒有漏洞正則判斷,需要大量的測試,通常最終結(jié)果非常負(fù)責(zé)

過濾篩選字符串,網(wǎng)絡(luò)爬蟲

替換文字,QQ聊天,圖文混排

語法規(guī)則

swift中的正則表達(dá)式小結(jié)

swift中的正則表達(dá)式小結(jié)

使用過程

1、創(chuàng)建規(guī)則

2、創(chuàng)建正則表達(dá)式對象

3、開始匹配

代碼示例

 

 
  1. private func check(str: String) { 
  2. // 使用正則表達(dá)式一定要加try語句 
  3. do { 
  4. // - 1、創(chuàng)建規(guī)則 
  5. let pattern = "[1-9][0-9]{4,14}" 
  6. // - 2、創(chuàng)建正則表達(dá)式對象 
  7. let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) 
  8. // - 3、開始匹配 
  9. let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)) 
  10. // 輸出結(jié)果 
  11. for checkingRes in res { 
  12. print((str as NSString).substringWithRange(checkingRes.range)) 
  13. catch { 
  14. print(error) 

其他幾個常用方法

 

 
  1. // 匹配字符串中所有的符合規(guī)則的字符串, 返回匹配到的NSTextCheckingResult數(shù)組 
  2. public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult]  
  3. // 按照規(guī)則匹配字符串, 返回匹配到的個數(shù) 
  4. public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int 
  5.  
  6. // 按照規(guī)則匹配字符串, 返回第一個匹配到的字符串的NSTextCheckingResult 
  7. public func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult? 
  8.  
  9. // 按照規(guī)則匹配字符串, 返回第一個匹配到的字符串的范圍 
  10. public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange 

使用子類來匹配日期、地址、和URL

看官網(wǎng)文檔解釋,可以知道這個 NSDataDetector 主要用來匹配日期、地址、和URL。在使用時指定要匹配的類型

 

 
  1. public class NSDataDetector : NSRegularExpression { 
  2. // all instance variables are private 
  3. /* 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. 
  4. */ 
  5. public init(types checkingTypes: NSTextCheckingTypes) throws 
  6. public var checkingTypes: NSTextCheckingTypes { get } 
  7. // 這個是類型選擇 
  8. public static var Date: NSTextCheckingType { get } // date/time detection 
  9. public static var Address: NSTextCheckingType { get } // address detection 
  10. public static var Link: NSTextCheckingType { get } // link detection 

NSDataDetector 獲取URL示例

 

 
  1. /** 
  2. 匹配字符串中的URLS 
  3.  
  4. - parameter str: 要匹配的字符串 
  5. */ 
  6. private func getUrl(str:String) { 
  7. // 創(chuàng)建一個正則表達(dá)式對象 
  8. do { 
  9. let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue)) 
  10. // 匹配字符串,返回結(jié)果集 
  11. let res = dataDetector.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)) 
  12. // 取出結(jié)果 
  13. for checkingRes in res { 
  14. print((str as NSString).substringWithRange(checkingRes.range)) 
  15. catch { 
  16. print(error) 

".*?" 可以滿足一些基本的匹配要求

如果想同時匹配多個規(guī)則 ,可以通過 "|" 將多個規(guī)則連接起來

將字符串中文字替換為表情

 

 
  1. /** 
  2. 顯示字符中的表情 
  3. - parameter str: 匹配字符串 
  4. */ 
  5. private func getEmoji(str:String) { 
  6. let strM = NSMutableAttributedString(string: str) 
  7. do { 
  8. let pattern = "//[.*?//]" 
  9. let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) 
  10. let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count)) 
  11. var count = res.count 
  12. // 反向取出文字表情 
  13. while count > 0 { 
  14. let checkingRes = res[--count] 
  15. let tempStr = (str as NSString).substringWithRange(checkingRes.range) 
  16. // 轉(zhuǎn)換字符串到表情 
  17. if let emoticon = EmoticonPackage.emoticonWithStr(tempStr) { 
  18. print(emoticon.chs) 
  19. let attrStr = EmoticonTextAttachment.imageText(emoticon, font: 18) 
  20. strM.replaceCharactersInRange(checkingRes.range, withAttributedString: attrStr) 
  21. print(strM) 
  22. // 替換字符串,顯示到label 
  23. emoticonLabel.attributedText = strM 
  24. catch { 
  25. print(error) 

TextKit 給URL高亮顯示

主要用到三個類

NSTextStorage

NSLayoutManager

NSTextContainer

自定義UILabel來實現(xiàn)url高亮

1、定義要用到的屬性

 

 
  1. /* 
  2. 只要textStorage中的內(nèi)容發(fā)生變化, 就可以通知layoutManager重新布局 
  3. layoutManager重新布局需要知道繪制到什么地方, 所以layoutManager就會文textContainer繪制的區(qū)域 
  4. */ 
  5. // 準(zhǔn)們用于存儲內(nèi)容的 
  6. // textStorage 中有 layoutManager 
  7. private lazy var textStorage = NSTextStorage() 
  8. // 專門用于管理布局 
  9. // layoutManager 中有 textContainer 
  10. private lazy var layoutManager = NSLayoutManager() 
  11. // 專門用于指定繪制的區(qū)域 
  12. private lazy var textContainer = NSTextContainer() 
  13. override init(frame: CGRect) { 
  14. super.init(frame: frame) 
  15. setupSystem() 
  16. required init?(coder aDecoder: NSCoder) { 
  17. super.init(coder: aDecoder) 
  18. setupSystem() 
  19. private func setupSystem() 
  20. // 1.將layoutManager添加到textStorage 
  21. textStorage.addLayoutManager(layoutManager) 
  22. // 2.將textContainer添加到layoutManager 
  23. layoutManager.addTextContainer(textContainer) 
  24. override func layoutSubviews() { 
  25. super.layoutSubviews() 
  26. // 3.指定區(qū)域 
  27. textContainer.size = bounds.size 

2、重寫label的text屬性

 

 
  1. override var text: String? 
  2. didSet{ 
  3. // 1.修改textStorage存儲的內(nèi)容 
  4. textStorage.setAttributedString(NSAttributedString(string: text!)) 
  5. // 2.設(shè)置textStorage的屬性 
  6. textStorage.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSMakeRange(0, text!.characters.count)) 
  7. // 3.處理URL 
  8. self.URLRegex() 
  9. // 2.通知layoutManager重新布局 
  10. setNeedsDisplay() 

3、匹配字符串

 

 
  1. func URLRegex() 
  2. // 1.創(chuàng)建一個正則表達(dá)式對象 
  3. do
  4. let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue)) 
  5. let res = dataDetector.matchesInString(textStorage.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, textStorage.string.characters.count)) 
  6. // 4取出結(jié)果 
  7. for checkingRes in res 
  8. let str = (textStorage.string as NSString).substringWithRange(checkingRes.range) 
  9. let tempStr = NSMutableAttributedString(string: str) 
  10. // tempStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, str.characters.count)) 
  11. tempStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()], range: NSMakeRange(0, str.characters.count)) 
  12. textStorage.replaceCharactersInRange(checkingRes.range, withAttributedString: tempStr) 
  13. }catch 
  14. print(error) 

4、重繪文字

 

 
  1. // 如果是UILabel調(diào)用setNeedsDisplay方法, 系統(tǒng)會促發(fā)drawTextInRect 
  2. override func drawTextInRect(rect: CGRect) { 
  3. // 重繪 
  4. // 字形 : 理解為一個小的UIView 
  5. /* 
  6. 第一個參數(shù): 指定繪制的范圍 
  7. 第二個參數(shù): 指定從什么位置開始繪制 
  8. */ 
  9. layoutManager.drawGlyphsForGlyphRange(NSMakeRange(0, text!.characters.count), atPoint: CGPointZero) 

獲取label中URL的點擊

如果要獲取URL的點擊,那么必須獲取點擊的范圍

 

 
  1. override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
  2. // 1、獲取手指點擊的位置 
  3. let touch = (touches as NSSet).anyObject()! 
  4. let point = touch.locationInView(touch.view) 
  5. print(point) 
  6. // 2、獲取URL區(qū)域 
  7. // 注意: 沒有辦法直接設(shè)置UITextRange的范圍 
  8. let range = NSMakeRange(10, 20) 
  9. // 只要設(shè)置selectedRange, 那么就相當(dāng)于設(shè)置了selectedTextRange 
  10. selectedRange = range 
  11. // 給定指定的range, 返回range對應(yīng)的字符串的rect 
  12. // 返回數(shù)組的原因是因為文字可能換行 
  13. let array = selectionRectsForRange(selectedTextRange!) 
  14. for selectionRect in array { 
  15. if CGRectContainsPoint(selectionRect.rect, point) { 
  16. print("點擊了URL"

以上內(nèi)容就是小編跟大家介紹的swift中的正則表達(dá)式小結(jié),希望大家喜歡。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 国产一区二区国产 | gril hd| 成人在线观看网 | 国产日产精品一区二区三区四区 | 免费看黄色一级大片 | 久久精品视频网站 | 欧美中文日韩 | 国产午夜精品久久久久久久蜜臀 | 日韩精品a在线观看 | 亚洲影院在线播放 | 亚洲国产精品二区 | 看毛片电影 | a在线视频| 美国人成人在线视频 | 91国内精品久久久久免费影院 | 久久亚洲线观看视频 | 日本最新免费二区三区 | 美女福利视频国产 | 久久99精品久久久久久国产越南 | 成人18免费观看 | 欧美激情视频一区二区免费 | 国产精品片一区二区三区 | 国产剧情v888av| 黄色一级视频 | 4399一级成人毛片 | 亚洲成人第一区 | 精品久久久久久久久中文字幕 | 国产色视频免费 | 又黄又爽免费无遮挡在线观看 | 精品中文视频 | 操操操操网 | 精品一区二区三区免费毛片 | 全黄性色大片 | 久久精品亚洲成在人线av网址 | 激情视频在线播放 | 亚洲性视频 | 欧美女孩videos | 日韩av在线资源 | 中文字幕在线观看国产 | 在线播放中文 | 国产日韩久久久久69影院 |