今日分享-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
    }

可以自己尝试下看看效果

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