Created
February 2, 2015 09:33
-
-
Save M-Medhat/a793c3163b4fbbe46976 to your computer and use it in GitHub Desktop.
Regular Expressions: How to replace patterns in Swift
This file contains hidden or 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
// You need to import Foundation to use NSRegularExpression, NSError and NSString | |
import Foundation | |
/// This function takes three parameters | |
/// text: a string that we search in | |
/// pattern: a reqular expression pattern to use in the search | |
/// withTemplate: the string that we use instead of the occurrances we find in text | |
/// | |
/// The method returns (text) with occurrance found using (pattern) replaced with (withTemplate) | |
func regexReplace(text:String, pattern:String, withTemplate:String) -> String { | |
// Assign text to a local variable as text is immutable | |
var _text = text | |
// Create an NSError object to use with NSReqularExpression. Initialize with nil | |
var error:NSError? = nil | |
// Create an object of type NSRegularExpression. We'll call this objects methods to perform | |
// RegEx operations, in this case, replacement. The object is initialized with three parameters | |
// the (pattern) used in the search, (options) in this case we're using CaseInsensitive search | |
// and (error) a pointer to an NSError object to assign errors to in case any errors happen. | |
let regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error) | |
// We're calling stringByReplacingMatchesInString on the regex object. The method accepts four paramteres: | |
// the (text) to search in, (options) in this case, none, the (range) to search in, in the string and here we're searching | |
// the whole string and finally (withTemplate) contains the value to be used. | |
// In case we succeed, assign the updated text to _text variable. | |
if let replacement = regex?.stringByReplacingMatchesInString(text, options: nil, range: NSMakeRange(0, countElements(text)), withTemplate: withTemplate) { | |
_text = replacement | |
} else { | |
// If the error object is not nil print the error discrption. | |
if((error) != nil) { | |
print(error?.description) | |
} | |
} | |
// return the final string | |
return _text | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi M-Medhat, very useful code, thank you for sharing. Do you have also a Swift 2 version?