Created
July 6, 2018 08:46
-
-
Save watanabetoshinori/37f5bac79fc3f656f46c8711b6c78257 to your computer and use it in GitHub Desktop.
String extension to replace text using Regular Expression
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
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