我有一根绳子
var text = "the {animal} jumped over the {description} fox"
和一本字典
var dictionary = ["animal":"dog" , "description", "jumped"]
我正在编写一个函数,用字典中的适当值替换大括号中的文本。我想为此使用正则表达式。
//alpha numeric characters, - and _
let regex = try NSRegularExpression(pattern: "{[a-zA-Z0-9-_]}", options: .caseInsensitive)
var text = "the {animal} jumped over the {description} fox"
let all = NSRange(location: 0, length: text.count)
regex.enumerateMatches(in: text, options: [], range: all) { (checkingResult, matchingFlags, _) in
guard let resultRange = checkingResult?.range else {
print("error getting result range")
return
}
//at this point, i was hoping that (resultRange.lowerbound, resultRange,upperBound) would be the start and end index of my regex match.
//so print(text[resultRange.lowerBound..<resultRange.upperBound] should give me {animal}
//so i could get the word between the curly braces, and replace it in the sentence with it dictionary value
}
但是快速的字符串操作对我来说非常令人困惑,而且这似乎不起作用。
这是正确的方向吗?
Thanks