有很多方法可以实现你想要的,但我认为最简单的方法之一是:
let newArray = arrayString
.replacingOccurrences(of: "[", with: "")
.replacingOccurrences(of: "]", with: "")
.replacingOccurrences(of: "\"", with: "")
.components(separatedBy: ",")
输出应该是:
["One", " Two", " Three", " Four"]
编辑:
正如@MartinR 建议的那样,如果任何字符串包含逗号或方括号,则先前的答案将不起作用。因此,要解决此问题,您可以删除方括号,假设在开头和结尾当然总是存在,然后使用正则表达式匹配 \"()\" 中的所有内容,如下面的代码:
让我们使用以下函数来匹配正则表达式:
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
更多参考可以看@MartinR 回答here
有了这个函数,我们可以使用下面的代码来实现我们想要的:
let str = "[\"One[\",\"T,w,o,\",\"Thr,ee,,,\",\"Fo,ur,,,\"]"
// remove the square brackets from the array
let start = str.index(str.startIndex, offsetBy: 1)
let end = str.index(str.endIndex, offsetBy: -1)
let range = start..<end
let newString = str.substring(with: range)
// match the regex
let matched = matches(for: "(?<=\")(.*?)(?=\")", in: newString) // ["One[", ",", "T,w,o,", ",", "Thr,ee,,,", ",", "Fo,ur,,,"]
但之前的 matched 包含数组中的 ",",所以让我们使用以下代码修复它:
let stringArray = matched.enumerated()
.filter { $0.offset % 2 == 0 }
.map { $0.element }
输出如下:
["One[", "T,w,o,", "Thr,ee,,,", "Fo,ur,,,"]
希望对你有帮助。