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

标签 regex swift swift3

假设我有以下 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/

相关文章:

regex - 解析ns2跟踪文件

ios - 如何调整 UITableViewController 中的部分和行?

ios - UIRefreshControl 出现在 Collection View 项的顶部而不是后面

regex - 正则表达式,匹配特定字符串后的单引号

JAVA:用户定义标记的正则表达式

php - preg_match 在验证 Windows 文件系统路径时没有按预期运行

ios - 使用日期 Swift 3 对字典数组进行排序

swift - 如何快速将核心数据管理对象数组转换为 "identifiable"列表? (Xcode 11,测试版 5)

调用 .append 时,Swift 字符串数组不保存数据

ios - 如何成功传递字符串数组作为参数 alamofire