Swift extract regex matches

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

    Even if the matchesInString() method takes a String as the first argument, it works internally with NSString, and the range parameter must be given using the NSString length and not as the Swift string length. Otherwise it will fail for "extended grapheme clusters" such as "flags".

    As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range and NSRange.

    func matches(for regex: String, in text: String) -> [String] {
    
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: text,
                                        range: NSRange(text.startIndex..., in: text))
            return results.map {
                String(text[Range($0.range, in: text)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
    

    Example:

    let string = "

提交回复
热议问题