Swift extract regex matches

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

    This is a very simple solution that returns an array of string with the matches

    Swift 3.

    internal func stringsMatching(regularExpressionPattern: String, options: NSRegularExpression.Options = []) -> [String] {
            guard let regex = try? NSRegularExpression(pattern: regularExpressionPattern, options: options) else {
                return []
            }
    
            let nsString = self as NSString
            let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
    
            return results.map {
                nsString.substring(with: $0.range)
            }
        }
    

提交回复
热议问题