Last active
November 11, 2023 22:50
-
-
Save laevandus/8851bde5f72443aa7ca88a5132bae75c 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
let text = "The quick <color_1> <animal_1> jumps over the lazy <animal_2>" | |
let replacementMap = ["<animal_1>": "fox", "<animal_2>": "dog", "<color_1>": "brown"] | |
extension String { | |
func replacingOccurrences(matchingPattern pattern: String, replacementProvider: (String) -> String?) -> String { | |
let expression = try! NSRegularExpression(pattern: pattern, options: []) | |
let matches = expression.matches(in: self, options: [], range: NSRange(startIndex..<endIndex, in: self)) | |
return matches.reversed().reduce(into: self) { (current, result) in | |
let range = Range(result.range, in: current)! | |
let token = String(current[range]) | |
guard let replacement = replacementProvider(token) else { return } | |
current.replaceSubrange(range, with: replacement) | |
} | |
} | |
} | |
let finalString1 = text.replacingOccurrences(matchingPattern: "<[:alpha:]+_{1}[:digit:]+>", replacementProvider: { replacementMap[$0] }) | |
let finalString2 = text.replacingOccurrences(matchingPattern: "<[:alpha:]+_{1}[:digit:]+>", replacementProvider: { _ in "REPLACEMENT" }) | |
print(text) | |
print(finalString1) // The quick brown fox jumps over the lazy dog | |
print(finalString2) // The quick REPLACEMENT REPLACEMENT jumps over the lazy REPLACEMENT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found your gist helpful - thanks!
Then saw another option with
Regex
: