Swift extract regex matches

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

    If you want to extract substrings from a String, not just the position, (but the actual String including emojis). Then, the following maybe a simpler solution.

    extension String {
      func regex (pattern: String) -> [String] {
        do {
          let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
          let nsstr = self as NSString
          let all = NSRange(location: 0, length: nsstr.length)
          var matches : [String] = [String]()
          regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
            (result : NSTextCheckingResult?, _, _) in
            if let r = result {
              let result = nsstr.substringWithRange(r.range) as String
              matches.append(result)
            }
          }
          return matches
        } catch {
          return [String]()
        }
      }
    } 
    

    Example Usage:

    "someText 

提交回复
热议问题