RJH RJH - 1 month ago 14
Swift Question

Regex find/replace list of keys (Swift 3)

I have a HTML file embedded into my xCode project which has tags within it such as:




I load the contents of the file into a String with:

let url = Bundle.main.url(forResource: "emailTemplate", withExtension: "html")
var messageBody:NSString!

do { messageBody = try String(contentsOf: url!) as NSString! }
catch { messageBody = "" }

Now I have populated "messageBody" I need to find and replace the tags based on my UI, for example:

1) find "{DESCRIPTION}" and replace it with lblDescription.text

2) find "{LOCATION}" and replace it with lblLocation.text

I am trying to use code similar to:

messageBody.enumerateSubstrings(in: NSMakeRange(0, messageBody.length), options: .byWords) { (substring, substringRange, enclosingRange, _) -> () in

However, I am completely useless with regex and could do with some assistance to find and replace if the substring equals a tag. Any ideas please?


You don't need regex for this. Repeated calls to replacingOccurrences will do:

import Foundation

let emailTemplate = "Hello {USER}\n" +
    "{DESCRIPTION}\n" +
    "\n" +

let email = emailTemplate
                .replacingOccurrences(of: "{USER}", with: "John Smith")
                .replacingOccurrences(of: "{DESCRIPTION}", with: "Have a nice day")