使用多个分隔符在swift中拆分字符串

时间:2015-09-08 18:49:31

标签: ios string swift split

我正在尝试使用多个分隔符或Apple调用它们的分隔符来拆分(或爆炸)Swift(1.2)中的字符串。

我的字符串如下所示:

KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value

我已将其格式化以便于阅读:

KEY1=subKey1=value&subkey2=value
KEY2=subkey1=value&subkey2=value
KEY3=subKey1=value&subkey3=value

大写的“KEY”是预定义的名称。 我试图这样做:

var splittedString = string.componentsSeparatedByString("KEY1")

但正如你所看到的,我只能用一个KEY作为分隔符,所以我正在寻找这样的东西:

var splittedString = string.componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])

结果将是:

[
  "KEY1" => "subKey1=value&subkey2=value",
  "KEY2" => "subkey1=value&subkey2=value",
  "KEY3" => "subkey1=value&subkey2=value"
]

我可以使用Swift 1.2内置的东西吗? 或者是否有某种扩展/库可以轻松实现?

感谢您的时间,祝您度过愉快的一天!

6 个答案:

答案 0 :(得分:7)

如果键是单个字符,也可以使用以下方法拆分具有多个分隔符的字符串:

let stringData = "K01L02M03"
let res = stringData.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "KLM"));

res将包含["01", "02", "03"]

如果有人知道任何一种特殊的语法来扩展每个键的多个字符的方法,欢迎你提出建议并改进这个答案

答案 1 :(得分:2)

这不是非常有效,但它应该完成这项工作:

import Foundation

extension String {
  func componentsSeperatedByStrings(ss: [String]) -> [String] {
    let inds = ss.flatMap { s in
      self.rangeOfString(s).map { r in [r.startIndex, r.endIndex] } ?? []
    }
    let ended = [startIndex] + inds + [endIndex]
    let chunks = stride(from: 0, to: ended.count, by: 2)
    let bounds = map(chunks) { i in (ended[i], ended[i+1]) }
    return bounds
      .map { (s, e) in self[s..<e] }
      .filter { sl in !sl.isEmpty }
  }
}



"KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value".componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])

// ["=subKey1=value&subkey2=value", "=subkey1=value&subkey2=value", "=subKey1=value&subkey3=value"]

或者,如果你想要它以字典形式:

import Foundation

extension String {
  func componentsSeperatedByStrings(ss: [String]) -> [String:String] {
    let maybeRanges = ss.map { s in self.rangeOfString(s) }
    let inds   = maybeRanges.flatMap { $0.map { r in [r.startIndex, r.endIndex] } ?? [] }
    let ended  = [startIndex] + inds + [endIndex]
    let chunks = stride(from: 0, to: ended.count, by: 2)
    let bounds = map(chunks) { i in (ended[i], ended[i+1]) }
    let values = bounds
      .map { (s, e) in self[s..<e] }
      .filter { sl in !sl.isEmpty }
    let keys = filter(zip(maybeRanges, ss)) { (r, _) in r != nil }
    var result: [String:String] = [:]
    for ((_, k), v) in zip(keys, values) { result[k] = v }
    return result
  }
}


"KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value".componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])

// ["KEY3": "=subKey1=value&subkey3=value", "KEY2": "=subkey1=value&subkey2=value", "KEY1": "=subKey1=value&subkey2=value"]

对于Swift 2:

import Foundation

extension String {
  func componentsSeperatedByStrings(ss: [String]) -> [String] {
    let unshifted = ss
      .flatMap { s in rangeOfString(s) }
      .flatMap { r in [r.startIndex, r.endIndex] }
    let inds  = [startIndex] + unshifted + [endIndex]
    return inds.startIndex
      .stride(to: inds.endIndex, by: 2)
      .map { i in (inds[i], inds[i+1]) }
      .flatMap { (s, e) in s == e ? nil : self[s..<e] }
  }
}

答案 2 :(得分:2)

Swift 4.2更新为@vir us's answer

const arrOfObj = [
  { 'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd' },
  { 'a': 'aa', 'b': 'bb', 'c': 'cc', 'd': 'dd' },
  { 'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd' }
];

const result = arrOfObj.map(({a, b}) => ({a, b}));

console.log(result);

答案 3 :(得分:0)

你可以用正则表达式来做。下面的片段有点笨拙,并不是真正的失败安全,但它应该给你一个想法。

let string = "KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value"
let re = NSRegularExpression(pattern: "(KEY1|KEY2|KEY3)=", options: nil, error: nil)!
let matches = re.matchesInString(string, options: nil,
    range: NSMakeRange(0, count(string)))

var dict = [String: String]()

for (index, match) in enumerate(matches) {
    let key = (string as NSString).substringWithRange(
        NSMakeRange(match.range.location, match.range.length - 1))

    let valueStart = match.range.location + match.range.length
    let valueEnd = index < matches.count - 1 ? matches[index + 1].range.location
                                             : count(string)
    let value = (string as NSString).substringWithRange(
        NSMakeRange(valueStart, valueEnd - valueStart))

    dict[key] = value
}

dict的最终值是

[KEY3: subKey1=value&subkey3=value, 
 KEY2: subkey1=value&subkey2=value,
 KEY1: subKey1=value&subkey2=value]

答案 4 :(得分:0)

Swift 2用于向前兼容性

使用正则表达式:

let string  = "KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value"
let nsString :NSString = string
let stringRange = NSMakeRange(0, string.utf16.count)
let pattern = "(KEY\\d)=([^=]+=[^&]+[^=]+?=[^K]+)"
var results = [String:String]()
do {
    var regEx = try NSRegularExpression(pattern:pattern, options:[])
    regEx.enumerateMatchesInString(string, options: [], range: stringRange) {
        (result : NSTextCheckingResult?, _, _) in
        if let result = result {
            if result.numberOfRanges == 3 {
                let key   = nsString.substringWithRange(result.rangeAtIndex(1))
                let value = nsString.substringWithRange(result.rangeAtIndex(2))
                results[key] = value
            }
        }
    }
}
catch {
    print("Bad Pattern")
}

结果:["KEY3": "subKey1=value&subkey3=value", "KEY2": "subkey1=value&subkey2=value", "KEY1": "subKey1=value&subkey2=value"]

答案 5 :(得分:0)

迅速5:

delete

这是为了存放精美的代码,如果您需要高效的东西,请不要使用它