• 可能的解决方案:
1. 分隔所有元素(分隔符:空格)
2. 2 2 迭代并使用键/值系统,例如Dictionary。
3. 之后从键中读取每个值
第 1 步:
let string = "A.1 value1 B.2 value2 E value3 C value4"
let components = string.components(separatedBy: CharacterSet.whitespaces)
第 2 步:
var dictionary: [String: String] = [:]
stride(from: 0, to: components.count - 1, by: 2).forEach({
dictionary[components[$0]] = components[$0+1]
})
或
let dictionary = stride(from: 0, to: components.count - 1, by: 2).reduce(into: [String: String]()) { (result, currentInt) in
result[components[currentInt]] = components[currentInt+1]
}
dictionary 是["A.1": "value1", "C": "value4", "E": "value3", "B.2": "value2"]
Inspiration 表示我很少使用的stride(from:to:)。
第 3 步:
let name = dictionary["A.1"]
let surname = dictionary["C"]
• 潜在问题:
如果你有:
let string = "A.1 value One B.2 value2 E value3 C value4"
你想要“value One”,因为有一个空格,你会遇到一些问题,因为 if 会给出错误的结果(因为有分隔符)。
你会得到: ["A.1": "value", "One": "B.2", "value2": "E", "value3": "C"] for dictionary。
因此您可以使用正则表达式:A.1(.*)B.2(.*)E(.*)C(.*)(例如)。
let string = "A.1 value One B.2 value2 E value3 C value4"
let regex = try! NSRegularExpression(pattern: "A.1(.*)B.2(.*)E(.*)C(.*)", options: [])
regex.enumerateMatches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) { (result, flags, stop) in
guard let result = result,
let aValueRange = Range(result.range(at: 1), in: string),
let bValueRange = Range(result.range(at: 2), in: string),
let cValueRange = Range(result.range(at: 4), in: string),
let eValueRange = Range(result.range(at: 3), in: string) else { return }
let aValue = string[aValueRange].trimmingCharacters(in: CharacterSet.whitespaces)
print("aValue: \(aValue)")
let bValue = string[bValueRange].trimmingCharacters(in: CharacterSet.whitespaces)
print("bValue: \(bValue)")
let cValue = string[cValueRange].trimmingCharacters(in: CharacterSet.whitespaces)
print("cValue: \(cValue)")
let eValue = string[eValueRange].trimmingCharacters(in: CharacterSet.whitespaces)
print("eValue: \(eValue)")
}
输出:
$>aValue: value One
$>bValue: value2
$>cValue: value4
$>eValue: value3
请注意,修剪可能在正则表达式内,但我不特别喜欢过于复杂的正则表达式。