【问题标题】:How to use NSRegular Expression and filter string array correctly in Swift如何在 Swift 中正确使用 NSRegular Expression 和过滤字符串数组
【发布时间】:2020-09-11 20:08:32
【问题描述】:

这是我的问题,我有一个字符串数组,其中包含一堆 国家:

让 myCountryStart = ["Africa/ABC", "America/BBC", "Asia/CBC", "Pacific/CBA", "Europe/CBB", "Indian/CAB"]

是否有任何解决方案可以删除特定单词,例如 “非洲”、“美国”、“亚洲”……等等。 让输出结果如下所示:

让 myCountryEnd = ["ABC", "BBC", "CBC", "CBA", "CBB", "CAB"]

这是我现在的代码...

let 1stReplace = myCountryStart.replacingOccurrences(of: "/", with: "", options: .literal)
let 2ndReplace = 1stReplace.replacingOccurrences(of: "Africa", with: "", options: .literal)
let 3rdReplace = 2ndReplace.replacingOccurrences(of: "Asia", with: "", options: .literal)

我知道这是一个愚蠢的解决方案。因此,我更喜欢使用 NSRegular Expression。但是我遇到了一个问题 关于字符串和字符串数组的问题。

let target = myCountryStart
let regex = "/"
let RE = try? NSRegularExpression(pattern: "regex", options: .caseInsensitive)
let modified = RE?.stringByReplacingMatches(in: target, options: .reportProgress, range: nil, withTemplate: "") {
    return modified
}
let myCountryEnd = modified

因此,我收到一条警告说我不能在 String 上使用此方法 大批。我该怎么做才能解决它?

任何建议或帮助将不胜感激。感谢 Swift 菜鸟。

【问题讨论】:

  • myCountryStart 似乎只有一个元素。这是真的吗?
  • 旧代码中的outputStr是什么?为什么不在新代码中使用它,而不是 myCountryStart
  • 应该是一个字符串数组的六个元素。我忘记修改了。
  • @Sweeper 感谢您通知我有关旧代码错误的信息。
  • 您没有在编辑中将其更改为 6 个元素...

标签: ios arrays swift regex string


【解决方案1】:

您可以使用 .*/^[^/]*/ 之类的正则表达式来使用 .map.replacingOccurrences

let myCountryStart = ["Africa/ABC", "America/BBC", "Asia/CBC", "Pacific/CBA", "Europe/CBB", "Indian/CAB"]
let myCountryEnd = myCountryStart.map{ $0.replacingOccurrences(of: ".*/", with: "", options: [.caseInsensitive,.regularExpression]) }
print(myCountryEnd)
// => ["ABC", "BBC", "CBC", "CBA", "CBB", "CAB"]

.*/ 模式将尽可能匹配除换行符以外的任何 0 个或多个字符,直到最后一个 /

^[^/]*/ 模式将匹配除 / 之外的任何字符,从字符串的开头到第一个 /

请注意,您不需要 .caseInsensitive 选项,我保留它是为了展示如何在 options 参数中组合多个选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2021-06-06
    • 1970-01-01
    • 2019-04-04
    • 2022-01-16
    相关资源
    最近更新 更多