3

I wrote extension that create split method:

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.

Thanks,

snaggs
  • 5,543
  • 17
  • 64
  • 127
  • I'd start with this method here: https://news.ycombinator.com/item?id=7890148. Run that, break off the string until the start of the found range and keep doing it until it returns `NSNotFound`. – Alex Wayne Aug 13 '14 at 21:05

1 Answers1

10

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.

extension String {
    func split(regex pattern: String) -> [String] {
        let template = "-|*~~*~~*|-" /// Any string that isn't contained in the original string (self).

        let regex = try? NSRegularExpression(pattern: pattern)
        let modifiedString = regex?.stringByReplacingMatches(
            in: self,
            range: NSRange(
                location: 0,
                length: count
            ),
            withTemplate: template /// Replace with the template/stop string.
        )
        
        /// Split by the replaced string.
        return modifiedString?.components(separatedBy: template) ?? []
    }
}
aheze
  • 24,434
  • 8
  • 68
  • 125
Mundi
  • 79,884
  • 17
  • 117
  • 140