Swift extract regex matches

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

    The fastest way to return all matches and capture groups in Swift 5

    extension String {
        func match(_ regex: String) -> [[String]] {
            let nsString = self as NSString
            return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, count)).map { match in
                (0..

    Returns a 2-dimentional array of strings:

    "prefix12suffix fix1su".match("fix([0-9]+)su")
    

    returns...

    [["fix12su", "12"], ["fix1su", "1"]]
    
    // First element of sub-array is the match
    // All subsequent elements are the capture groups
    

提交回复
热议问题