gpt4 book ai didi

regex - 如何在swift中通过正则表达式过滤字典键

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

假设我有以下 Swift 字典:

var studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led  Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]

我想要一本只包含“Led Zeppelin...”的新词典(即 Led Zeppelin、Led Zeppelin II、...、Led Zeppelin IV)。

我已经为 Dictionary 和 Array 创建了扩展方法 https://stackoverflow.com/a/41435190/7384373

然后我可以使用字符串“range of”方法来查找“Led Zeppelin”,如下所示:

let filtered = studioAlbums.filteredDictionary( { $0.0.range(of: "Led Zeppelin") != nil } )

// print(filtered) output: "["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin": 1969, "Led Zeppelin II": 1969]\n"

我的问题是关于更复杂的过滤我更愿意使用正则表达式 (regex),但我无法用 Regex 找出任何简单的解决方案,假设最多 5 行代码。 (不包括任何扩展方法)。

最佳答案

我认为这是您正在寻找的扩展:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
func filterDictionaryUsingRegex(withRegex regex: String) -> Dictionary<Key, Value> {
return self.filter({($0.key as! String).range(of: regex, options: .regularExpression) != nil}).toDictionary(byTransforming: {$0})
}
}

扩展仅限于 <String, Any> 类型的词典以避免任何 Key 到 String 的转换错误。

结果:

let studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led  Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
let filtered = studioAlbums.filterDictionaryUsingRegex(withRegex: "Led")
// ["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin ": 1969, "Led Zeppelin II": 1969]

编辑:这确实需要 user7367341 的扩展: Filtering Dictionary Stack Overflow Question

extension Array
{
func toDictionary<H:Hashable, T>(byTransforming transformer: (Element) -> (H, T)) -> Dictionary<H, T>
{
var result = Dictionary<H,T>()
self.forEach({ element in
let (key,value) = transformer(element)
result[key] = value
})
return result
}
}

关于regex - 如何在swift中通过正则表达式过滤字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508527/

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