RJH RJH - 9 days ago 4
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:

{DESCRIPTION}

{LOCATION}

{TIME_SUBMITTED}

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
print(substring!)
}


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?

Answer

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

import Foundation

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

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