user4432964
user4432964

Reputation:

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 ) ?

Upvotes: 1

Views: 574

Answers (2)

OOPer
OOPer

Reputation: 47876

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"]

Upvotes: 0

Code Different
Code Different

Reputation: 93141

Try this:

// Subscripting a String with NSRange. Make dealing with ObjC-classes easier
extension String {
    subscript(range: NSRange) -> String {
        let startIndex = self.startIndex.advancedBy(range.location)
        let endIndex = startIndex.advancedBy(range.length)

        return self[startIndex..<endIndex]
    }
}

let str = "0lY6P5Ur90TAQnnnI6wtnb,#29,Projekt-FZK-Haus,Projekt FZK-House create by KHH Forschuungszentrum Karlsruhe,$,$,$,(#67,#229,#275),#42"
let regex = try! NSRegularExpression(pattern: "\\((#[^\\)]+)\\)", options: [])

if let match = regex.firstMatchInString(str, options: [], range: NSMakeRange(0, str.characters.count)) {
    let substr = str[match.rangeAtIndex(1)]
    let components = substr.componentsSeparatedByString(",")

    print(components)
}

Upvotes: 2

Related Questions