在swift中从string中提取值

时间:2016-07-07 21:16:23

标签: ios regex swift

我有一个如下所示的字符串,我试图将每个部分(,)分成一个数组。

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

0lY6P5Ur90TAQnnnI6wtnb,#29,Projekt-FZK-Haus,Projekt FZK-House创建   作者:KHH Forschuungszentrum Karlsruhe,$,$,$,(#67,#229,#275),#42

结果

has_many :favorites, -> { order("favorite_photos.id ASC") }, through: :favorite_photos, source: :photo

如果您注意到,(#67,#229,#275)部分被分为“(#67”,“#229”,“#275)”

我想将这些值插入(大括号)到另一个数组中。所以我的问题是,如何找到开头然后结束

2 个答案:

答案 0 :(得分:2)

试试这个:

// 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)
}

答案 1 :(得分:0)

另一个例子。正确使用基于UTF-16的索引和范围,因此可以使用包括非BMP字符的字符串。

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