String find and replace
sharplet opened this issue · 0 comments
sharplet commented
I think it would be worth supporting some find and replace functions with support for back-references. Here's the API I have in mind:
extension String {
/// Replace the first occurrence of `pattern` with `replacement`.
func stringByReplacingFirstMatching(pattern: String, with replacement: String) -> String
/// Replace all occurrences of `pattern` with `replacement`.
func stringByReplacingAllMatching(pattern: String, with replacement: String) -> String
/// Mutating form of `stringByReplacingFirstMatching(_:with:)`.
mutating func replaceFirstMatching(pattern: String, with replacement: String)
/// Mutating form of `stringByReplacingAllMatching(_:with:)`.
mutating func replaceAllMatching(pattern: String, with replacement: String)
}
We should be able to implement this with NSRegularExpression.stringByReplacingMatchesInString(_:options:range:withTemplate:)
and NSRegularExpression.replaceMatchesInString(_:options:range:withTemplate:)
.