Skip to content

Instantly share code, notes, and snippets.

@ayyybe
Created October 4, 2020 07:55
Show Gist options
  • Save ayyybe/1aa1d4d57c2252a7361d6f129fd34ff5 to your computer and use it in GitHub Desktop.
Save ayyybe/1aa1d4d57c2252a7361d6f129fd34ff5 to your computer and use it in GitHub Desktop.
var parse thing
import Cocoa
var vars = [
"AdobeCommon": "/Library/Application Support/Adobe",
"df": "shouldn't get replaced",
"durq": "wurqd!",
"AdobeProgramFiles": "/Applications"
]
func parseVars(_ str: String) -> String {
var out = str
var substr = Substring(str)
while let closeIndex = substr.lastIndex(of: "]") {
substr = str[..<closeIndex]
guard let openIndex = substr.lastIndex(of: "[") else {
break
}
let name = String(str[str.index(openIndex, offsetBy: 1)..<closeIndex])
if let value = vars[name] {
out.replaceSubrange(openIndex...closeIndex, with: value)
}
}
return out
}
let str = "asdfsdfkdj[AdobeCommon]][[df[]]testtt2][[durq]]"
print(str)
print(parseVars(str))
print(parseVars("[AdobeProgramFiles]/Adobe Photoshop 2020"))
// => asdfsdfkdj[AdobeCommon]][[df[]]testtt2][[durq]]
// => asdfsdfkdj/Library/Application Support/Adobe][[df[]]testtt2][wurqd!]
// => /Applications/Adobe Photoshop 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment