Created
February 17, 2017 02:26
-
-
Save jayrhynas/9ee2da1b99f4c91ee3914310ba1c489f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 quotedSplit(separator: String = " ", quote: String = "\"") -> [String] { | |
| let escapedQuote = "\\\(quote)" | |
| var parts: [String] = [] | |
| var quotedPart: String? = nil | |
| for part in self.componentsSeparatedByString(separator) { | |
| var part = part | |
| if let quoted = quotedPart { | |
| var ending = false | |
| if part.hasSuffix(quote) && !part.hasSuffix(escapedQuote) { | |
| part = part.substringToIndex(part.endIndex.predecessor()) | |
| ending = true | |
| } | |
| part = part.stringByReplacingOccurrencesOfString(escapedQuote, withString: quote) | |
| let newPart = "\(quoted) \(part)" | |
| if ending { | |
| parts.append(newPart) | |
| quotedPart = nil | |
| } else { | |
| quotedPart = newPart | |
| } | |
| } | |
| else if part.hasPrefix(quote) { | |
| quotedPart = part.substringFromIndex(part.startIndex.successor()) | |
| .stringByReplacingOccurrencesOfString(escapedQuote, withString: quote) | |
| } | |
| else { | |
| parts.append(part) | |
| } | |
| } | |
| return parts | |
| } | |
| } | |
| extension SequenceType where Generator.Element == String { | |
| func quotedJoin(separator: String = " ", quote: String = "\"") -> String { | |
| let escapedQuote = "\\\(quote)" | |
| return self.map { element in | |
| let element = element.stringByReplacingOccurrencesOfString(quote, withString: escapedQuote) | |
| if element.rangeOfString(separator) != nil { | |
| return "\(quote)\(element)\(quote)" | |
| } else { | |
| return element | |
| } | |
| }.joinWithSeparator(separator) | |
| } | |
| } | |
| // let tagList = "WRLD \"NEST \\\"HQ\\\" MiniMix\" \"NEST HQ\"" | |
| // tagList.quotedSplit().forEach { print($0) } | |
| // | |
| let tags = ["WRLD", "NEST \"HQ\" MiniMix", "NEST HQ"] | |
| print(tags.quotedJoin()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment