gpt4 book ai didi

ios - 用字典中的正确值替换字符串中匹配的正则表达式值

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:54 26 4
gpt4 key购买 nike

我有一个字符串

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
}

但是快速的字符串操作让我非常困惑,这似乎行不通。

这是正确的方向吗?

谢谢

最佳答案

这是一种有效的解决方案。字符串处理更加复杂,因为您还必须处理 NSRange

extension String {
func format(with parameters: [String: Any]) -> String {
var result = self

//Handles keys with letters, numbers, underscore, and hyphen
let regex = try! NSRegularExpression(pattern: "\\{([-A-Za-z0-9_]*)\\}", options: [])

// Get all of the matching keys in the curly braces
let matches = regex.matches(in: self, options: [], range: NSRange(self.startIndex..<self.endIndex, in: self))

// Iterate in reverse to avoid messing up the ranges as the keys are replaced with the values
for match in matches.reversed() {
// Make sure there are two matches each
// range 0 includes the curly braces
// range 1 includes just the key name in the curly braces
if match.numberOfRanges == 2 {
// Make sure the ranges are valid (this should never fail)
if let keyRange = Range(match.range(at: 1), in: self), let fullRange = Range(match.range(at: 0), in: self) {
// Get the key in the curly braces
let key = String(self[keyRange])
// Get that value from the dictionary
if let val = parameters[key] {
result.replaceSubrange(fullRange, with: "\(val)")
}
}
}
}

return result
}
}

var text = "the {animal} jumped over the {description} fox"
var dictionary = ["animal":"dog" , "description": "jumped"]
print(text.format(with: dictionary))

输出:

the dog jumped over the jumped fox

如果在字典中找不到,此代码会将原始 {keyname} 保留在字符串中。根据需要调整该代码。

关于ios - 用字典中的正确值替换字符串中匹配的正则表达式值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com