Skip to content

Instantly share code, notes, and snippets.

@xinmyname
Created April 1, 2018 15:52
Show Gist options
  • Save xinmyname/4a698948943eea12fce0bc918aeef96d to your computer and use it in GitHub Desktop.
Save xinmyname/4a698948943eea12fce0bc918aeef96d to your computer and use it in GitHub Desktop.
Split and replace strings in swift
//: Playground - noun: a place where people can play
import Cocoa
extension String {
//
func splitBetween(_ startText:String, and endText:String) -> [String]? {
guard let startIndex = self.range(of: startText)?.upperBound else {
return nil
}
guard let endIndex = self.range(of: endText)?.lowerBound else {
return nil
}
let text = String(self[startIndex..<endIndex])
return text.split(separator: ",").map { String($0) }
}
func replacingBetween(_ startText:String, and endText:String, with:String) -> String? {
guard let startIndex = self.range(of: startText)?.upperBound else {
return nil
}
guard let endIndex = self.range(of: endText)?.lowerBound else {
return nil
}
var newText = String(self)
newText.replaceSubrange(startIndex..<endIndex, with: with)
return newText
}
}
let text="<html><head><magic>4,8,15,16,23,42</magic></head><body>blah, blah, blah</body></html>"
let numbers = text.splitBetween("<magic>", and: "</magic>")
let elements = text.replacingBetween("<magic>", and: "</magic>", with: "fire,air,water,earth")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment