这是我的问题,我有一个包含一堆国家的字符串数组:
让myCountryStart = [“非洲/ ABC”,“美国/ BBC”,“亚洲/ CBC”,“太平洋/ CBA”,“欧洲/ CBB”,“印度/ CAB”]
是否有任何解决方案来删除“ Africa”,“ America”,“ Asia” ...等特定单词。让输出结果如下所示:
让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个或多个字符,并尽可能地匹配到last /
。
该^[^/]*/
模式将匹配/
从字符串开头到第一个以外的所有字符/
。
请注意,您不需要该.caseInsensitive
选项,我保留了它来显示如何在options
参数中组合多个选项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句