Swift extract regex matches

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

    Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

    To get the capture group matches as expected you need something like (Swift4) :

    public extension String {
        public func capturedGroups(withRegex pattern: String) -> [String] {
            var results = [String]()
    
            var regex: NSRegularExpression
            do {
                regex = try NSRegularExpression(pattern: pattern, options: [])
            } catch {
                return results
            }
            let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))
    
            guard let match = matches.first else { return results }
    
            let lastRangeIndex = match.numberOfRanges - 1
            guard lastRangeIndex >= 1 else { return results }
    
            for i in 1...lastRangeIndex {
                let capturedGroupIndex = match.range(at: i)
                let matchedString = (self as NSString).substring(with: capturedGroupIndex)
                results.append(matchedString)
            }
    
            return results
        }
    }
    

提交回复
热议问题