欧美一级特黄大片做受成人-亚洲成人一区二区电影-激情熟女一区二区三区-日韩专区欧美专区国产专区

如何正確的在swift中使用正則表達(dá)式

今天就跟大家聊聊有關(guān)如何正確的在swift中使用正則表達(dá)式,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

創(chuàng)新互聯(lián)建站專業(yè)提供成都主機(jī)托管四川主機(jī)托管成都服務(wù)器托管四川服務(wù)器托管,支持按月付款!我們的承諾:貴族品質(zhì)、平民價格,機(jī)房位于中國電信/網(wǎng)通/移動機(jī)房,樂山服務(wù)器托管服務(wù)有保障!

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

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

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

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

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

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

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

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

語法規(guī)則

如何正確的在swift中使用正則表達(dá)式

如何正確的在swift中使用正則表達(dá)式

使用過程

1、創(chuàng)建規(guī)則
2、創(chuàng)建正則表達(dá)式對象
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á)式對象
  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)
 }
}

其他幾個常用方法        

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

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

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

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 }
}
// 這個是類型選擇
 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)建一個正則表達(dá)式對象
 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)
 }
}

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

如果想同時匹配多個規(guī)則 ,可以通過 "|" 將多個規(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高亮顯示

主要用到三個類

NSTextStorage
NSLayoutManager
NSTextContainer

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

1、定義要用到的屬性

 /*
 只要textStorage中的內(nèi)容發(fā)生變化, 就可以通知layoutManager重新布局
 layoutManager重新布局需要知道繪制到什么地方, 所以layoutManager就會文textContainer繪制的區(qū)域
 */
 // 準(zhǔn)們用于存儲內(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存儲的內(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)建一個正則表達(dá)式對象
  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)會促發(fā)drawTextInRect
override func drawTextInRect(rect: CGRect) {
 // 重繪
 // 字形 : 理解為一個小的UIView
 /*
 第一個參數(shù): 指定繪制的范圍
 第二個參數(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對應(yīng)的字符串的rect
 // 返回數(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á)式有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

分享題目:如何正確的在swift中使用正則表達(dá)式
文章源于:http://www.aaarwkj.com/article6/psoiog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站網(wǎng)站內(nèi)鏈、手機(jī)網(wǎng)站建設(shè)品牌網(wǎng)站制作、全網(wǎng)營銷推廣定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作
亚洲欧美不卡一区二区| 伊人久久精品一区二区| 欧美日韩精品一区二区视频永久免 | av一区二区三区高潮| 青青草原一区在线观看| 久久国产福利一区二区| 精品综合亚洲中文字幕| 国产精品久久久久久老熟女| 精品国产一区二区日韩91| 欧美福利区免费观看视频| 精品视频中文字幕天码| 久久99热这里只频精品| 在线观看高清欧美国产视频| 国产一级黄色片免费看| 熟女熟妇乱女乱妇综合网| 97热久久精品中文字幕一区| 欧美一区二区三区日| 欧美精品一区二区三区色| 日韩一级黄色片在线播放| 欧美日韩黄色在线观看| 国产麻豆91精品女同性恋| 日本一区二区欧美在线| 成人福利午夜一区二区| 亚洲一区二区三区日本久久| 国产av手机自拍看片| 国产三级视频在线观看视频 | av在线中文字幕剧情| 国产av剧情日韩精品| 变态另类欧美国产在线| 日本av天堂中文字幕| 欧美口爆吞精在线观看| 国产一区在线免费在线观看| 色综合亚洲一区二区小说| 人妻操人人妻中出av| 欧美午夜精品福利在线观看| 亚洲国产欧美在线人成人| 婷婷六月开心激情五月| 99精品人妻一区二区三区| 国产日韩欧在线视频| 亚洲国产日韩欧美第一页| 偷窥偷拍视频一区二区|