1986914 1986914 - 5 months ago 15
Swift Question

Extract values from string in swift

I have a string as shown below and i am trying to separate each part (,) into an array.

let stringArr = remainderString.componentsSeparatedByString(",")



0lY6P5Ur90TAQnnnI6wtnb,#29,Projekt-FZK-Haus,Projekt FZK-House create
by KHH Forschuungszentrum Karlsruhe,$,$,$,(#67,#229,#275),#42


Results

["0lY6P5Ur90TAQnnnI6wtnb", "#29", "Projekt-FZK-Haus", "Projekt FZK-House create by KHH Forschuungszentrum Karlsruhe", "$", "$", "$", "(#67", "#229", "#275)", "#42"]


If you notice, the part (#67,#229,#275) were separated into "(#67", "#229", "#275)"

I want to insert those values inside the (braces) into an another array. So my question is, how can I locate the opening ( and then the closing ) ?

Answer

Another example. Using UTF-16 based index and range properly, so works with Strings including non-BMP characters.

let str = "0lY6P5Ur90TAQnnnI6wtnb,#29,Projekt-FZK-Haus,Projekt FZK-House create by KHH Forschuungszentrum Karlsruhe,$,$,$,(#67,#229,#275),#42"
let pattern = "(\\([^\\)]*\\)|[^\\(,][^,]*)(?:,|$)"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(str, options: [], range: NSRange(0..<str.utf16.count))
let stringArr = matches.map{match->String in
    let matchingRange = match.rangeAtIndex(1)
    let matchingString = (str as NSString).substringWithRange(matchingRange) as String
    return matchingString
}
print(stringArr) //->["0lY6P5Ur90TAQnnnI6wtnb", "#29", "Projekt-FZK-Haus", "Projekt FZK-House create by KHH Forschuungszentrum Karlsruhe", "$", "$", "$", "(#67,#229,#275)", "#42"]