这是我的问题,我有一个字符串数组,其中包含一串
国家:
让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/