swift 允许正则表达式在swift中扩展

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 允许正则表达式在swift中扩展相关的知识,希望对你有一定的参考价值。

//extension that allows to test for a match in a string
extension String {
    func matchPattern(patStr:String)->Bool {
        var isMatch:Bool = false
        do {
            let regex = try NSRegularExpression(pattern: patStr, options: [.CaseInsensitive])
            let result = regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count))
            
            if (result != nil)
            {
                isMatch = true
            }
        }
        catch {
            isMatch = false
        }
        return isMatch
    }
}

"hello sir".matchPattern("^h.+")
//extension that allows for matches in a string to be extracted
extension String {
    func matchesForRegexInText(regex: String!) -> [String] {
        
        do {
            let regex = try NSRegularExpression(pattern: regex, options: [])
            let nsString = self as NSString
            let results = regex.matchesInString(self,
                options: [], range: NSMakeRange(0, nsString.length))
            return results.map { nsString.substringWithRange($0.range)}
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
}

"5 is good 5y 58 5f".matchesForRegexInText("5.")

以上是关于swift 允许正则表达式在swift中扩展的主要内容,如果未能解决你的问题,请参考以下文章

swift swift中的正则表达式扩展

格式化货币 - Swift

匹配正则表达式的字符串扩展

Regex 正则表达式中几个符号([ ] ^ ?: ?= ?!)的概念

在 Swift 中使用特殊字符转义正则表达式

swift 在swift中设置字符串,使正则表达式搜索在极端空间的O(1)中进行。