import Foundation
let pattern = #"[:]\s(\".*\")|\d+"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
{
"code": 0,
"data": {
"album": {
"count": 2,
"itemlist": [
{
"docid": "24100646",
"id": "24100646",
"mid": "002mPgSG01LLtu",
"name": "无名的人",
"pic": "http://y.gtimg.cn/music/photo_new/T002R180x180M000002mPgSG01LLtu_1.jpg",
"singer": "毛不易"
},
{
"docid": "3834888",
"id": "3834888",
"mid": "0026ttFc17IeE3",
"name": "无问",
"pic": "http://y.gtimg.cn/music/photo_new/T002R180x180M0000026ttFc17IeE3_1.jpg",
"singer": "毛不易"
}
],
"name": "专辑",
"order": 2,
"type": 3
},
"mv": {
"count": 2,
"itemlist": [
{
"docid": "1449642",
"id": "1449642",
"mid": "001UwAbv4H9QVZ",
"name": "牧马城市",
"singer": "毛不易",
"vid": "k002671le5d"
},
{
"docid": "1352908",
"id": "1352908",
"mid": "003bjsSu20ltwY",
"name": "像我这样的人",
"singer": "毛不易",
"vid": "y0026hr4b5e"
}
],
"name": "MV",
"order": 3,
"type": 4
},
"singer": {
"count": 2,
"itemlist": [
{
"docid": "1507534",
"id": "1507534",
"mid": "001BHDR33FZVZ0",
"name": "毛不易",
"pic": "http://y.gtimg.cn/music/photo_new/T001R150x150M000001BHDR33FZVZ0_3.jpg",
"singer": "毛不易"
},
{
"docid": "4417724",
"id": "4417724",
"mid": "000pEm1i1BkmuD",
"name": "毛不易的留声机",
"pic": "http://y.gtimg.cn/music/photo_new/T001R150x150M000000pEm1i1BkmuD_1.jpg",
"singe": "毛不易的留声机"
}
],
"name": "歌手",
"order": 1,
"type": 2
},
"song": {
"count": 4,
"itemlist": [
{
"docid": "203514624",
"id": "203514624",
"mid": "00375L600p9sxv",
"name": "像我这样的人",
"singer": "毛不易"
}
{
"docid": "203451421",
"id": "203451421",
"mid": "003kLvu04bLGzi",
"name": "消愁",
"singer": "毛不易"
}
{
"docid": "213224236",
"id": "213224236",
"mid": "000uhMwj387EBp",
"name": "牧马城市",
"singer": "毛不易"
}
{
"docid": "336582682",
"id": "336582682",
"mid": "002QhULf16tWw1",
"name": "无名的人",
"singer": "毛不易"
}
],
"name": "单曲",
"order": 0,
"type": 1
}
},
"subcode": 0
}
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression