How to create String split extension with regex in Swift?

前端 未结 1 1221
鱼传尺愫
鱼传尺愫 2021-01-03 13:24

I wrote extension that create split method:

extension String {
    func split(splitter: String) -> Array {
        return self.         


        
相关标签:
1条回答
  • 2021-01-03 14:17

    First, your split function has some redundancy. It is enough to return

    return self.componentsSeparatedByString(splitter)
    

    Second, to work with a regular expression you just have to create a NSRegularExpression and then perhaps replace all occurrences with your own "stop string" and finally separate using that. E.g.

    let regEx = NSRegularExpression.regularExpressionWithPattern
      (splitter, options: NSRegularExpressionOptions(), error: nil)
    let stop = "SomeStringThatYouDoNotExpectToOccurInSelf"
    let modifiedString = regEx.stringByReplacingMatchesInString
         (self, options: NSMatchingOptions(), 
                  range: NSMakeRange(0, countElements(self)), 
           withTemplate:stop)
    return modifiedString.componentsSeparatedByString(stop)
    
    0 讨论(0)
提交回复
热议问题