千家信息网

如何正确的在swift中使用正则表达式

发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,今天就跟大家聊聊有关如何正确的在swift中使用正则表达式,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。正则表达式的用处:判断给定的字符串是否
千家信息网最后更新 2026年11月02日如何正确的在swift中使用正则表达式

今天就跟大家聊聊有关如何正确的在swift中使用正则表达式,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

正则表达式的用处:

判断给定的字符串是否符合某一种规则(专门用于操作字符串)

- 电话号码,电子邮箱,URL...

- 可以直接百度别人写好的正则

- 别人真的写好了,而且测试过了,我们可以直接用

- 要写出没有漏洞正则判断,需要大量的测试,通常最终结果非常负责

过滤筛选字符串,网络爬虫

替换文字,QQ聊天,图文混排

语法规则

使用过程

1、创建规则
2、创建正则表达式对象
3、开始匹配

代码示例

private func check(str: String) { // 使用正则表达式一定要加try语句 do {  // - 1、创建规则  let pattern = "[1-9][0-9]{4,14}"  // - 2、创建正则表达式对象  let regex = try NSRegular_Expression(pattern: pattern, options: 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) }}

其他几个常用方法

 // 匹配字符串中所有的符合规则的字符串, 返回匹配到的NSTextCheckingResult数组      public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult]            // 按照规则匹配字符串, 返回匹配到的个数      public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int            // 按照规则匹配字符串, 返回第一个匹配到的字符串的NSTextCheckingResult      public func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult?            // 按照规则匹配字符串, 返回第一个匹配到的字符串的范围      public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange

使用子类来匹配日期、地址、和URL

看官网文档解释,可以知道这个 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) { // 创建一个正则表达式对象 do {  let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(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) }}

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

如果想同时匹配多个规则 ,可以通过 "|" 将多个规则连接起来

将字符串中文字替换为表情

 /**显示字符中的表情- parameter str: 匹配字符串*/private func getEmoji(str:String) { let strM = NSMutableAttributedString(string: str) do {  let pattern = "\\[.*?\\]"  let regex = try NSRegular_Expression(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)   // 转换字符串到表情   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来实现url高亮

1、定义要用到的属性

 /* 只要textStorage中的内容发生变化, 就可以通知layoutManager重新布局 layoutManager重新布局需要知道绘制到什么地方, 所以layoutManager就会文textContainer绘制的区域 */ // 准们用于存储内容的 // textStorage 中有 layoutManager private lazy var textStorage = NSTextStorage() // 专门用于管理布局 // layoutManager 中有 textContainer private lazy var layoutManager = NSLayoutManager() // 专门用于指定绘制的区域 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.指定区域   textContainer.size = bounds.size }

2、重写label的text属性

override var text: String?  {  didSet{ // 1.修改textStorage存储的内容 textStorage.setAttributedString(NSAttributedString(string: text!)) // 2.设置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.创建一个正则表达式对象  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取出结果   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调用setNeedsDisplay方法, 系统会促发drawTextInRectoverride func drawTextInRect(rect: CGRect) { // 重绘 // 字形 : 理解为一个小的UIView /* 第一个参数: 指定绘制的范围 第二个参数: 指定从什么位置开始绘制 */ layoutManager.drawGlyphsForGlyphRange(NSMakeRange(0, text!.characters.count), atPoint: CGPointZero)}

获取label中URL的点击

如果要获取URL的点击,那么必须获取点击的范围

 override func touchesBegan(touches: Set, withEvent event: UIEvent?) { // 1、获取手指点击的位置 let touch = (touches as NSSet).anyObject()! let point = touch.locationInView(touch.view) print(point) // 2、获取URL区域 // 注意: 没有办法直接设置UITextRange的范围 let range = NSMakeRange(10, 20) // 只要设置selectedRange, 那么就相当于设置了selectedTextRange selectedRange = range // 给定指定的range, 返回range对应的字符串的rect // 返回数组的原因是因为文字可能换行 let array = selectionRectsForRange(selectedTextRange!) for selectionRect in array {   if CGRectContainsPoint(selectionRect.rect, point) {    print("点击了URL")   } }}

看完上述内容,你们对如何正确的在swift中使用正则表达式有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

字符 字符串 正则 规则 表达式 内容 文字 结果 区域 对象 布局 范围 表情 属性 位置 参数 地址 多个 数组 方法 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网金融科技 北京路客互联网科技有限公司 互联网科技会 互联网核心科技是什么 互联网巨头反垄断金融科技 朗涯互联网科技 善班互联网科技有限公司 狮子座互联网科技培训 互联网科技论坛 老年人脱离互联网科技的作文 移动互联网科技股 厦门比较好的科技互联网公司 滨湖区互联网智能科技产品有哪些 宇信科技在杭州互联网排第几 下一代互联网重大应用科技园 山东大美朱楼互联网科技有限公司 互联网科技包装股 银川新华互联网科技学校原画 科技和互联网行业的特点 杭州科技互联网公司有哪些 互联网科技有限公司 翻译 互联网 科技服务平台 现代科技和互联网有关系吗 阿里互联网科技公司 贵州叶脉互联网科技有限公司所属行业 亳州好赞互联网科技有限公司 特约风豹互联网科技为什么扣费 启辰互联网科技 城市宝互联网科技有限公司 互联网科技资金流入
0