Swift extract regex matches

前端 未结 11 1938
无人及你
无人及你 2020-11-21 23:44

I want to extract substrings from a string that match a regex pattern.

So I\'m looking for something like this:

func matchesForRegexInText(regex: St         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 00:33

    My answer builds on top of given answers but makes regex matching more robust by adding additional support:

    • Returns not only matches but returns also all capturing groups for each match (see examples below)
    • Instead of returning an empty array, this solution supports optional matches
    • Avoids do/catch by not printing to the console and makes use of the guard construct
    • Adds matchingStrings as an extension to String

    Swift 4.2

    //: Playground - noun: a place where people can play
    
    import Foundation
    
    extension String {
        func matchingStrings(regex: String) -> [[String]] {
            guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
            let nsString = self as NSString
            let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
            return results.map { result in
                (0..

    Swift 3

    //: Playground - noun: a place where people can play
    
    import Foundation
    
    extension String {
        func matchingStrings(regex: String) -> [[String]] {
            guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
            let nsString = self as NSString
            let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
            return results.map { result in
                (0..

    Swift 2

    extension String {
        func matchingStrings(regex: String) -> [[String]] {
            guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
            let nsString = self as NSString
            let results  = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
            return results.map { result in
                (0..

提交回复
热议问题