Replace string with regex in swift
I want to replace a portion of a string that matches a regex pattern.
I have the following regex pattern:
And this is a string replacement pattern:
How can I use them inside Swift code?
Solutions Collect From Internet About “Replace string with regex in swift”
In Swift, you can use
stringByReplacingMatchesInString for a regex-based replace.
Here is a snippet showing how to use it:
let txt = "firstname.lastname@example.org" let regex = NSRegularExpression(pattern: "([^@\\s]+)@test\\.(\\w+)", options:nil, error: nil) let newString = regex!.stringByReplacingMatchesInString(txt, options: nil, range: NSMakeRange(0, count(txt)), withTemplate: "$1@hoge.$2") println(newString)
Note that I changed the regex to
([^@\\s]+)– matches 1 or more characters other than
test.literally and then 1 or more alphanumeric character (
Note that in the replacement string, you do not need to escape the period.
- How to upload image that was taken from UIImagePickerController
- Objective-C: How to format string as $ Price
- prepareForSegue called before didSelectRowAtIndexPath only when third segue is added
- Adding a circle mask layer on an UIImageView
- Resize UIImage and change the size of UIImageView
- : object cannot be nil
- Remote web application debugging not working in ios 8 beta
- Is it possible to use NSArray, NSDictionary, and NSNumber “literals” in Xcode 4.3? (LLVM 4.0)
- Making a Button Call a Phone Number in iOS
- How to Embed Ustream video into iOS
- Xcode 6.4 Export Adhoc “Session has expired”
- Objective C code base will work on Swift directly?
- ORDER BY random() with seed in SQLITE
- FCM – Programatically Send Push Notification To User Segments
- how to check if the iOS device is locked/unlocked using Swift?