今日分享-swift正則表達式的應用

正則表達式,又稱規則表達式。(英語:Regular Expression,在代碼中常簡寫爲regex、regexp或RE),計算機科學的一個概念。正則表通常被用來檢索、替換那些符合某個模式(規則)的文本。

關於正則表達式的文本規則可以在這片文章中搜索查看這裏寫鏈接內容

本文主要介紹正則表達式在siwft中的使用方式
NSRegularExpression 類是蘋果對正則表達式的封裝

@available(iOS 4.0, *)
open class NSRegularExpression : NSObject, NSCopying, NSSecureCoding {

    public init(pattern: String, options: NSRegularExpression.Options = []) throws

    open var pattern: String { get }

    open var options: NSRegularExpression.Options { get }

    open var numberOfCaptureGroups: Int { get }

    open class func escapedPattern(for string: String) -> String
}
extension NSRegularExpression {


    /* The fundamental matching method on NSRegularExpression is a block iterator.  There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match.  Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to rangeAtIndex:0) and any capture group ranges are given by rangeAtIndex: for indexes from 1 to numberOfCaptureGroups.  {NSNotFound, 0} is used if a particular capture group does not participate in the match.
    */

    open func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void)


    open func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult]

    open func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Int

    open func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSTextCheckingResult?

    open func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSRange
}

extension NSRegularExpression {


    /* NSRegularExpression also provides find-and-replace methods for both immutable and mutable strings.  The replacement is treated as a template, with $0 being replaced by the contents of the matched range, $1 by the contents of the first capture group, and so on.  Additional digits beyond the maximum required to represent the number of capture groups will be treated as ordinary characters, as will a $ not followed by digits.  Backslash will escape both $ and itself.
    */
    open func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> String

    open func replaceMatches(in string: NSMutableString, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> Int


    /* For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in case modifications to the string moved the result since it was matched), and a replacement template.
    */
    open func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String


    /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as template metacharacters. 
    */
    open class func escapedTemplate(for string: String) -> String
}

來看下使用

山上住着老和尚和小和尚。一天老和尚煮了飯,小和尚邊吃邊抱怨:山路不好走,寺院香火也不旺。等小和尚說完,老和尚問:飯菜味道如何?小和尚答,光顧說話沒留意。老和尚讓他再品,小和尚說,味道真好。老和尚微微一笑說:“當你在不停的抱怨時,就會忘了享受生活中當下的樂趣。”
把這句話中的’和尚’、’“’、’”’用紅色顯示出來,下面是處理過程:

        let str = "山上住着老和尚和小和尚。一天老和尚煮了飯,小和尚邊吃邊抱怨:山路不好走,寺院香火也不旺。等小和尚說完,老和尚問:飯菜味道如何?小和尚答,光顧說話沒留意。老和尚讓他再品,小和尚說,味道真好。老和尚微微一笑說:“當你在不停的抱怨時,就會忘了享受生活中當下的樂趣。”"

        let attribute = highLightWord(sentence: str, string: "和尚|“|”") //關於正則表達式的文本規則可以在這片文章中搜索查看(http://blog.csdn.net/xuzenghuifeng/article/details/72627357)

  func highLightWord(sentence:String,string:String)->NSMutableAttributedString {

        let attributestring = NSMutableAttributedString.init(string: sentence as String, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)])

         let regex = try! NSRegularExpression.init(pattern: string, options:NSRegularExpression.Options(rawValue: 0))
        let matches = regex.matches(in: sentence, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0,sentence.characters.count - 1))

        for (_,item) in matches.enumerated() {

            let range = item.range
            attributestring.setAttributes([NSFontAttributeName : UIFont.boldSystemFont(ofSize: 16), NSForegroundColorAttributeName : UIColor.red], range: range)
        }

        return attributestring
    }

可以自己嘗試下看看效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章