У меня есть строка
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
}
, но быстрое манипулирование струнами меня невероятно смущает, и это, похоже, не работает.
Это правильное направление?
Спасибо