ios - 如何在Swift中正确使用NSRegular Expression和过滤字符串数组

标签 ios arrays swift regex string

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

让myCountryStart = [“非洲/ ABC”,“美国/ BBC”,“亚洲/ CBC”,“太平洋/ CBA”,“欧洲/ CBB”,“印度/ 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新秀。

最佳答案

您可以使用.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参数中组合多个选项。

关于ios - 如何在Swift中正确使用NSRegular Expression和过滤字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61998138/

相关文章:

arrays - 如何找到数组最大值的索引?

ios - Swift 中的惰性函数

ios - 将 alpha 设置为 0 以删除动画? - objective-c

ios - 如何从不同的 swift 文件调用函数

ios - 运行失败 'lipo' ,lib有相同的架构

java - 打印数组的索引号

copy_to_user 一个包含数组(指针)的结构

swift - 期望 SwiftUI DynamicProperty 属性包装器的内部更新来触发 View 更新是否正确?

ios - 为我的 iOS 应用创建指南(教程)

ios - 由于未捕获的异常 'NSInternalInconsistencyException' 错误而终止应用程序