Swift 2过滤字符串到数组

时间:2016-03-18 08:47:48

标签: arrays string swift2

是否有快速搜索和将字符串拆分为数组的解决方案?

例如,

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"

let UserIdArray = ["123", "321", "111", "222"]
let UserNameArray = ["Peter", "Joe", "Ken", "John"]

4 个答案:

答案 0 :(得分:2)

这是使用正则表达式和捕获组的解决方案

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"
var userIdArray = [String]()
var userNameArray = [String]()

let pattern = "userid[:\\s]+(\\d+)[\\s,]+userName[:\\s]+(\\w+)"

do {
  let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
  let result = regex.matchesInString(userList, options: NSMatchingOptions(), range: NSRange(location: 0, length: userList.characters.count))
  let nsUserList = userList as NSString
  for item in result {
    userIdArray.append(nsUserList.substringWithRange(item.rangeAtIndex(1)))
    userNameArray.append(nsUserList.substringWithRange(item.rangeAtIndex(2)))
  }
  print(userIdArray, userNameArray)
} catch let error as NSError {
  print(error)
}

答案 1 :(得分:1)

正则表达式可能会对此有所帮助。

在此处查看教程 - https://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial

会是这样的: "userName\s*:\s*([^,\s]+)(,|.|$)"

对于用户ID,只需将userName替换为userid

答案 2 :(得分:1)

'纯'快速解决方案

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"

let arr = userList.characters.split { ",. :".characters.contains($0) }.map(String.init)
let arrf = arr.filter { $0 != "userid" && $0 != "userName" }

var userId:[String] = []
var userName:[String] = []

for (i,v) in arrf.enumerate() {
    if i % 2 == 0 {
        userId.append(v)
    } else {
        userName.append(v)
    }
}

print(userId, userName) // ["123", "321", "111", "222"] ["Peter", "Joe", "Ken", "John"]

答案 3 :(得分:0)

试试这个简单的。

let arr = userList.componentsSeparatedByString(",")

var arrA:[String] = []
var arrB:[String] = []

for str in arr {
    let tmp = str.componentsSeparatedByString(":")

    arrA.append(tmp[0])
    arrB.append(tmp[1])
}

print(arrA)
print(arrB)

但我喜欢@Dmitry的答案