Skip to content

Instantly share code, notes, and snippets.

@nariakiiwatani
Last active September 5, 2018 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nariakiiwatani/25c9c7f0f6f5294fb358a8228549185d to your computer and use it in GitHub Desktop.
Save nariakiiwatani/25c9c7f0f6f5294fb358a8228549185d to your computer and use it in GitHub Desktop.
import Foundation
extension String {
func regexEscaped() -> String {
var str: String = self
"\\*+.?{}()[]-|$".forEach{
let s = String($0)
str = str.replacingOccurrences(of: s, with: "\\"+s)
}
return str
}
func trimming(withString str:String) -> String {
let str = str.regexEscaped()
return self.replacingOccurrences(of: "^"+str+"|"+str+"$", with: "", options: .regularExpression, range: nil)
}
public func split(withDelimiters delimiters:[String]=[" ", ","], andQuotes quotes:[String]=["\"", "'"]) -> [String] {
var dels = delimiters
dels.append(contentsOf: quotes)
dels = dels.map{$0.regexEscaped()}
var patterns = ["((?!"+dels.joined(separator:"|")+").)+"]
quotes.forEach{
let src = $0.regexEscaped()
patterns.append(src + "((?!" + src + ").)*" + src)
}
let regex = try! NSRegularExpression(pattern: patterns.joined(separator: "|"), options: [])
var arr = [String]()
regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.count))
.forEach{
var src = (self as NSString).substring(with: $0.range(at: 0))
let quote = quotes.filter{src.hasPrefix($0) && src.hasSuffix($0)}
if !quote.isEmpty {
src = src.trimming(withString:quote[0])
}
arr.append(src)
}
return arr
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment