swift swift中的正则表达式扩展

Posted

tags:

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

//
// Created by Joshua Weinstein on 4/29/16.
// Copyright (c) 2016 Geeni. All rights reserved.
//

import Foundation
//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
    }
}

//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 []
        }
    }
}

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

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

怎样在Swift中使用正则表达式

swift中的正则表达式

swift中的正则表达式不适用于此示例?

无法让 Swift 中的正则表达式匹配“不包含”

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