Swift - 匹配字符串中所有NSRange

有时候想对字符串进行某些特殊操作,需要获取NSRange,比如富文本...
下面简单在String上进行扩展,方便使用...
extension String {
    
    /// 字符串的匹配范围 方法一
    ///
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    func exMatchStrRange(matchStr: String) -> [NSRange] {
        var allLocation = [Int]() //所有起点
        let matchStrLength = (matchStr as NSString).length  //currStr.characters.count 不能正确统计表情
        let arrayStr = self.componentsSeparatedByString(matchStr)
        var currLoc = 0
        arrayStr.forEach { currStr in
            currLoc += (currStr as NSString).length
            allLocation.append(currLoc)
            currLoc += matchStrLength
        }
        allLocation.removeLast()
        return allLocation.map { NSRange(location: $0, length: matchStrLength) } //可把这段放在循环体里面,同步处理,减少再次遍历的耗时
    } 

    /// 字符串的匹配范围 方法二(推荐)
    ///
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    func exMatchStrNSRange(matchStr: String) -> [NSRange] {
        var selfStr = self as NSString
        var withStr = Array(count: (matchStr as NSString).length, repeatedValue: "X").joinWithSeparator("") //辅助字符串
        if matchStr == withStr { withStr = withStr.lowercaseString } //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.rangeOfString(matchStr).location != NSNotFound {
            let range = selfStr.rangeOfString(matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.stringByReplacingCharactersInRange(NSMakeRange(range.location, range.length), withString: withStr)
        }
        return allRange
    }
}

let str = "吾生也有涯而知也无涯,以有涯随无涯殆己"
let allRange1 = str.exMatchStrRange("无涯")
let allRange2 = str.exMatchStrNSRange("涯")
print(allRange1) //  [(8,2), (15,2)]
print(allRange2) //  [(4,1), (9,1), (13,1), (16,1)]

富文本使用例子:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let str = "吾生也有涯,而知也无涯。\n以有涯随无涯,殆已!\n已而为知者,殆而已矣!"
        let attributeString = NSMutableAttributedString(string: str)
        let allRange1 = str.exMatchStrRange("无涯")
        let allRange2 = str.exMatchStrRange("吾生")
        let allRange3 = str.exMatchStrRange("殆已")
        allRange1.forEach {
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: $0)
            attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,range: $0)
        }
        allRange2.forEach {
            attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 18)!,range: $0)
        }
        allRange3.forEach {
            attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.redColor(),
                range: $0)
        }
        label.attributedText = attributeString
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,403评论 19 139
  • 一个字符串 是一系列字符的集合,例如hello, world和albatross。Swift的字符串是String...
    BoomLee阅读 7,022评论 0 3
  • 最近有幸看到这本史蒂芬·柯维的代表作--《高效能人士的七个习惯》,他用七个习惯来分析对人的生活、工作、家庭的影响。...
    桃酥1618阅读 2,187评论 1 5
  • 一个满意的装修, 就能带给你无限的归属感. 它们从不言语, 却能带给你最安心的陪伴. 我们比你更懂得房子的意义; ...
    我叫黑名单阅读 1,443评论 0 0
  • 君问归期未有期 (诗人独自坐在窗前写信或思考。你要是问我什么时候回来,我也不知道) 巴山夜雨涨秋池 (我现在在秋天...
    菠00阅读 4,592评论 0 0