There can be a bunch of ways to achieve what you want, but I think one of the most easy is the following:
let newArray = arrayString
.replacingOccurrences(of: "[", with: "")
.replacingOccurrences(of: "]", with: "")
.replacingOccurrences(of: "\"", with: "")
.components(separatedBy: ",")
And the output should be:
["One", " Two", " Three", " Four"]
EDIT:
As @MartinR suggested the previous answer doesn't work if any of the strings contains a comma or a square bracket. So to fix that you can remove the square brackets supposing that always are there of course at the beginning and in the end and then use regex to match everything inside the \"()\"
like in the following code:
Let's use the following function to match regex:
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 []
}
}
For more reference, you can see the @MartinR answer here
With that function we can use the following code to achieve what we want:
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,,,"]
But the previous matched
include the ","
in the array so let's fix that with the following code:
let stringArray = matched.enumerated()
.filter { $0.offset % 2 == 0 }
.map { $0.element }
With the following output:
["One[", "T,w,o,", "Thr,ee,,,", "Fo,ur,,,"]
I hope this helps you.