2016-11-23 56 views
0

我有一個HTML文件嵌入到其內具有標籤比如我的Xcode項目:正則表達式查找/替換鍵列表(SWIFT 3)

{說明}

{LOCATION}

{TIME_SUBMITTED}

我的文件的內容加載到一個字符串:

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

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

現在我已填充「消息體」我需要根據我的UI查找和替換的標籤,例如:

1)找到「{描述衝」,並與lblDescription.text

2更換)找到「{}位置」,並與lblLocation.text

更換

我想使用類似代碼:

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

然而,我與正則表達式完全無用的,並且可以與一些援助做查找和替換如果子字符串等於一個標籤。請有任何想法嗎?

回答

1

你不需要這個正則表達式。重複撥打replacingOccurrences會做:

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) 
+0

非常好,謝謝! – RJH