-
-
Save chenjunpu/8f2953404f74e6e2c0bc62c255837c74 to your computer and use it in GitHub Desktop.
replace for Swift String (include replaceFirst and replaceAll), in Swift 3
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
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