Swift extract regex matches

前端 未结 11 1937
无人及你
无人及你 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:25

    Swift 4 without NSString.

    extension String {
        func matches(regex: String) -> [String] {
            guard let regex = try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) else { return [] }
            let matches  = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
            return matches.map { match in
                return String(self[Range(match.range, in: self)!])
            }
        }
    }
    

提交回复
热议问题