Skip to content

Instantly share code, notes, and snippets.

@watanabetoshinori
Created July 6, 2018 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watanabetoshinori/37f5bac79fc3f656f46c8711b6c78257 to your computer and use it in GitHub Desktop.
Save watanabetoshinori/37f5bac79fc3f656f46c8711b6c78257 to your computer and use it in GitHub Desktop.
String extension to replace text using Regular Expression
public extension String {
//
// Example
// "Hello World!".replace(pattern: "Hello (.*)", template: "Goodbye $1") -> "Goodbye World!"
//
func replace(pattern: String, template: String) -> String? {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let replacedString = regex.stringByReplacingMatches(in: self,
options: [],
range: NSRange(location: 0, length: count),
withTemplate: template)
return replacedString
} catch {
print(error)
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment