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)]

富文本使用例子:

Swift - 匹配字符串中所有NSRange_第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
    }
}

你可能感兴趣的:(Swift - 匹配字符串中所有NSRange)