Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Created August 24, 2016 06:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcxiaoke/b03f8c989c0cb36ccde50555b596f0f0 to your computer and use it in GitHub Desktop.
Save mcxiaoke/b03f8c989c0cb36ccde50555b596f0f0 to your computer and use it in GitHub Desktop.
replace for Swift String (include replaceFirst and replaceAll), in Swift 3
import Foundation
extension String {
public func replaceFirst(of pattern:String,
with replacement:String) -> String {
if let range = self.range(of: pattern){
return self.replacingCharacters(in: range, with: replacement)
}else{
return self
}
}
public func replaceAll(of pattern:String,
with replacement:String,
options: NSRegularExpression.Options = []) -> String{
do{
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(0..<self.utf16.count)
return regex.stringByReplacingMatches(in: self, options: [],
range: range, withTemplate: replacement)
}catch{
NSLog("replaceAll error: \(error)")
return self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment