Last active
September 5, 2018 00:34
-
-
Save nariakiiwatani/25c9c7f0f6f5294fb358a8228549185d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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