import Foundation
let pattern = #"(?s)^.*?\"longitude[^\[]*?\"activity[^\[]*\[[^\]]*?timestampMs\"[^\"\]]*\"(\d+)\"[^\]]*WALKING[^\]]*?confidence\"\s*:\s*(\b\d{1,3}\b)[^\]]*?\].*$"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
}, {
"timestampMs" : "1515564666086", ◁― Don't need this but it won't hurt
"latitudeE7" : -6857630899,
"longitudeE7" : -1779694452999,
"activity" : [ {
"timestampMs" : "1515564665992", ◁― EXAMPLE: I want only this, and...
"activity" : [ {
"type" : "STILL",
"confidence" : 65
}, {
"type" : "TILTING", ↓
"confidence" : 4
}, {
"type" : "IN_RAIL_VEHICLE",
"confidence" : 20
}, {
"type" : "IN_ROAD_VEHICLE",
"confidence" : 5
}, {
"type" : "ON_FOOT", ↓
"confidence" : 3
}, {
"type" : "UNKNOWN",
"confidence" : 3
}, {
"type" : "WALKING", ◁― ...AND, I also want this.
"confidence" : 3
} ]
} ]
}, {
"timestampMs" : "1515564662594", ◁― Don't need this but it won't hurt
"latitudeE7" : -6857630899,
"longitudeE7" : -1779694452999,
"altitude" : 42
}, {
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\1 \2"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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