snaggs snaggs - 1 year ago 128
Swift Question

How to create String split extension with regex in Swift?

I wrote extension that create


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

So in playground I can write:

var str = "Hello, playground"

if str.split(",").count > 1{
var out = str.split(",")[0]

println("output: \(out)") // output: Hello

What do I need to make it work with regex like in Java:

str.split("[ ]+")

Because this way it doesn't work.


Answer Source

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)), 
return modifiedString.componentsSeparatedByString(stop)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download