Swift extract regex matches

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

    Big thanks to Lars Blumberg his answer for capturing groups and full matches with Swift 4, which helped me out a lot. I also made an addition to it for the people who do want an error.localizedDescription response when their regex is invalid:

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

    For me having the localizedDescription as error helped understand what went wrong with escaping, since it's displays which final regex swift tries to implement.

提交回复
热议问题