iOS中正則表達式的使用

正則表達式的使用說明

正則表達式中用的枚舉

  1. 正則表達式匹配的方式 NSRegularExpression.Options
public struct Options : OptionSet {
        ///匹配字母,不區分大小寫。
        public static var caseInsensitive: NSRegularExpression.Options { get }
        /// 忽略模式中的空格和#前綴的註釋。
        public static var allowCommentsAndWhitespace: NSRegularExpression.Options { get }
        ///將整個模式視爲文字字符串。
        public static var ignoreMetacharacters: NSRegularExpression.Options { get }
        ///允許 "." 匹配任何字符,包括行分隔符。(在其他語言中"."匹配除“`\``n`”之外的任何單個字符,要匹配包括“`\``n`”在內的任何字符,請使用像“`(.|\n)`”的模式。)
        public static var dotMatchesLineSeparators: NSRegularExpression.Options { get }
        ///允許^和$匹配行的開頭和結尾。
        public static var anchorsMatchLines: NSRegularExpression.Options { get }
        ///僅將\n視爲行分隔符(否則,將使用所有標準行分隔符)。
        public static var useUnixLineSeparators: NSRegularExpression.Options { get }
        ///使用Unicode TR#29指定單詞邊界(否則,使用傳統的正則表達式單詞邊界)。
        public static var useUnicodeWordBoundaries: NSRegularExpression.Options { get }
    }
  1. 匹配選項常量指定表達式匹配方法匹配規則。 所有使用正則表達式搜索或替換值的方法都將使用這些常量。 NSRegularExpression.MatchingOptions
public struct MatchingOptions : OptionSet {
        ///找到最長的匹配字符串後調用block回調。 該選項對除enumerateMatches(in:options:range:using :)以外的方法無效。
        public static var reportProgress: NSRegularExpression.MatchingOptions { get } 
        ///完成任何匹配後,調用該塊一次。找到任何一個匹配串後都回調一次block
        public static var reportCompletion: NSRegularExpression.MatchingOptions { get }
        ///從匹配範圍的開始出進行極限匹配
        public static var anchored: NSRegularExpression.MatchingOptions { get } 
        ///允許匹配超出搜索範圍的範圍。
        public static var withTransparentBounds: NSRegularExpression.MatchingOptions { get }
        ///禁止^和$自動匹配搜索範圍的開始和結束。
        public static var withoutAnchoringBounds: NSRegularExpression.MatchingOptions { get }
    }

3.匹配進行,完成或失敗時,由block設置。 方法enumerateMatches(in:options:range:using :)使用。

public struct MatchingFlags : OptionSet {
        ///匹配到最長串時被設置
        public static var progress: NSRegularExpression.MatchingFlags { get }
        ///全部分配完成後被設置
        public static var completed: NSRegularExpression.MatchingFlags { get } 
        ///匹配到設置範圍的末尾時被設置
        public static var hitEnd: NSRegularExpression.MatchingFlags { get } 
        ///當前匹配到的字符串在匹配範圍的末尾時被設置
        public static var requiredEnd: NSRegularExpression.MatchingFlags { get }
        ///由於錯誤導致的匹配失敗時被設置
        public static var internalError: NSRegularExpression.MatchingFlags { get } 
    }

NSRegularExpression常用的方法

  1. NSRegularExpression的基本匹配方法。
open func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void)
  • 例子
///NSRegularExpression的基本匹配方法。
let  test = "abcdefabcghijkabclmn"
let  pattern = "abc"
let  re = try? NSRegularExpression.init(pattern: pattern, options: .caseInsensitive)
re?.enumerateMatches(in: test, options: .reportCompletion, range:NSRange.init(location: 0, length: test.count), using: { (result, flag, point) in
     guard let res = result else{
        return
     }
     print(res)
})
///輸出結果
/*
 <NSSimpleRegularExpressionCheckingResult: 0x1006896d0>{0, 3}{<NSRegularExpression: 0x10068c0d0> abc 0x1}
 <NSSimpleRegularExpressionCheckingResult: 0x1006896d0>{6, 3}{<NSRegularExpression: 0x10068c0d0> abc 0x1}
 <NSSimpleRegularExpressionCheckingResult: 0x1006896d0>{14, 3}{<NSRegularExpression: 0x10068c0d0> abc 0x1}
 */
  1. 查找結果以NSTextCheckingResult數組的形式返回
open func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult]
  • 例子
/// 查找結果以NSTextCheckingResult數組的形式返回
let test = "abcdefabcghijkabclmn"
let pattern = "abc"
let re = try? NSRegularExpression.init(pattern: pattern, options: .caseInsensitive)
let arr =  re?.matches(in: test, options: .reportCompletion, range: NSRange.init(location: 0, length: test.count))
arr?.forEach({ (result) in
    print(result)
})
/*
<NSSimpleRegularExpressionCheckingResult: 0x100671300>{0, 3}{<NSRegularExpression: 0x100673b70> abc 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x100671400>{6, 3}{<NSRegularExpression: 0x100673b70> abc 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x100671440>{14, 3}{<NSRegularExpression: 0x100673b70> abc 0x1}
*/
  1. 返回匹配結果到的個數
open func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Int
  • 例子
///返回匹配結果到的個數
let test = "abcdefabcghijkabclmn"
let pattern = "abc"
let re = try? NSRegularExpression.init(pattern: pattern, options: .caseInsensitive)
let num =  re?.numberOfMatches(in: test, options: .reportProgress, range: NSRange.init(location: 0, length: test.count))
print(num!)
///輸出結果
/*
 3
 */
  1. 返回匹配到的第一個結果(NSTextCheckingResult)
open func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSTextCheckingResult?
  1. 返回匹配到的第一個結果的range(NSRange)
open func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSRange
  1. 將匹配到的結果替換爲特定的字符串,並將替換後生成的新的字符串返回
open func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> String
  1. 將原字符串中匹配到的結果用指定的字符串替換,返回值爲Int類型,是匹配並替 換的個數
open func replaceMatches(in string: NSMutableString, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> Int
  1. 對於實現自己的替換功能的客戶端,這是一種對單個結果執行模板替換的方法,給定與結果匹配的字符串,將偏移量添加到字符串中的結果位置(例如, 如果對字符串進行了修改(由於已匹配)而移動了結果)和替換模板。
open func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String
  1. 此類方法將通過在給定字符串的必要位置添加反斜槓轉義符來生成字符串,以轉義將被當成模板元字符的字符。
open class func escapedTemplate(for string: String) -> String
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章