XZ_iOS之正则表达式和简单的图文混排

正则表达式

有关正则表达式的参考文档链接 http://deerchao.net/tutorials/regex/regex.htm

正则表达式不是 OC 特有的,几乎所有的语言/IDE,都支持正则表达式

iOS中的使用

最大用处:’匹配’字符串,进行’模糊查找’

  • 正则表达式常用选项

    • CaseInsensitive 忽略大小写

    • DotMatchesLineSeparators .匹配换行符

  • 匹配方案

    • . 匹配任意字符,回车除外
    • * 匹配 0~任意 多个字符
    • ? 尽可能少的重复
    • .*? 可以代替任何字符
  • 匹配函数

    • matchesInString
      • 重复匹配多次 pattern
      • 如果匹配成功,生成 NSTextCheckingResult 数组
    • firstMatchInString
      • 匹配第一个 pattern
      • 如果匹配成功,生成 NSTextCheckingResult
  • 匹配结果

    • numberOfRanges
      • 匹配的 range 计数,查找到的范围数量
      • 如果匹配成功,是()的数量 + 1
    • rangeAtIndex
      • 获取第几个子表达式
      • 指定’索引’位置的范围
1、在Xcode中的使用

将下图中,字典的key值设置为value中的颜色值
这里写图片描述

Replace:”(.?)”: UIColor.(.?),
With:” 2":UIColor\. 2,
修改完之后的结果:
这里写图片描述

2、取出指定范围内的文字

例如,取出<a href=\"http://www.baidu.com\" rel=\nofollow7\">百度一下</a> 中的链接,以及文本描述

pattern - 常说的正则表达式,就是 pattern 的写法[匹配方案]
索引:
0:和匹配方案完全一致的字符串
1:第一个 () 中的内容
2:第二个 () 中的内容
… 索引从左往右顺序递增

let string = "<a href=\"http://www.baidu.com\" rel=\"nofollow7\">百度一下</a>"
 // 2.创建正则表达式
 let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
 // 1>创建正则表达式,如果 pattern 失败,抛出异常
guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
    return
}

// 2>进行查找,两种查找方法
// [只找第一个匹配项/查找多个匹配项]
guard let result = regx.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) else {
    print("没有找到匹配项")
    return
}

print("找到的数量\(result.numberOfRanges)")
// 打印的结果:找到的数量3        

// 3> result 中只有两个重要的方法
// result.numberOfRanges -> 查找到的范围数量
// result.range(at: idx) -> 指定‘索引($2)’位置的范围
for idx in 0..<result.numberOfRanges {

    let range = result.range(at: idx)
    let subStr = (string as NSString).substring(with: range)

    print(range,subStr)
    // 打印的结果:
    /**
    {0, 55} <a href="http://www.baidu.com" rel="nofollow7">百度一下</a>
    {9, 20} http://www.baidu.com
    {47, 4} 百度一下
   */
}
3、使用正则表达式查找 URL 的范围数组

使用匹配 URL 的正则表达式,进行多重匹配,将查找到的范围放在数组 ranges 中,可以查找到字符串中的多个 URL,也可以使用 firstMatch 进行单一匹配

/// 返回 textStorage 中的 URL range 数组
    var urlRanges : [NSRange]? {
        // 1. url 的正则表达式
        let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*"

        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
            return nil
        }

        // 2.多重匹配
        let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))

        // 3.遍历数组,生成 range 的数组
        var ranges = [NSRange]()

        for m in matches {
            ranges.append(m.range(at: 0))
        }

        return ranges
    }
简单的图文混排

简单的图文混排最重要的就是将图片转换为图片属性文本,这就涉及到两个类的结合使用:NSAttributedString 和 NSTextAttachment
可以实现给 UILabel 添加图片的功能

/// 将当前的图像转换成图片属性文本
    func imageText(font: UIFont) -> NSAttributedString {
        // 1.判断图像是否存在
        guard let image = image else {
            return NSAttributedString.init(string: "")
        }

        // 2.创建文本附件
        let attchment = NSTextAttachment()

        attchment.image = image
        let height = font.lineHeight
        // 如果图片太高了,使用下面这句进行设置
        attchment.bounds = CGRect(x: 0, y: -4, width: height, height: height)

        // 3.返回图片属性文本
        return NSAttributedString(attachment: attchment)
    }

实现结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值