import Foundation
let pattern = #"\"locId\":\"(?<locId>[^\"]*)\",\"ip\":\"[^\"]*\",\"hostName\":\"[^\"]*\",\"macaddress\":\"(?<macaddress>[^\"]*)\""#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
{"bdy":{"msg":"NitrosApplication_OnLaunched event triggered.","metricName":"AppStart","metricValue":"NitrosApplication_OnLaunched","measuredTime":"00:00:00.7181610"},"hdr":{"level":"Information","timestamp":"2017-03-17T15:00:55.9692895Z","lineNum":0,"userId":"a211ba03eb3aa1","loc":"Store","locId":"0775","ip":"10.434.24.4","hostName":"W-W10ME-7534513","macaddress":"00-16-7F-EE-DD-17","eventid":0,"appVersion":"10.0.2","appName":"L"},"ver":"0.1"}
{"bdy":{"msg":"Background Task 'DevicePowerCheckBackgroundTask' is Running..."},"hdr":{"level":"Information","timestamp":"2017-03-17T15:00:55.842Z","fxsrc":"Run","lineNum":53,"loc":"Store","locId":"0320","ip":"10.439.3.11","hostName":"K-W10ME-054232","macaddress":"00-13-7F-13-33-29","eventid":0,"appVersion":"3.0.2","appName":"L"},"ver":"0.1"}
{"bdy":{"msg":"SplashPage loaded on back click.","metricName":"PageLoad","metricValue":"SplashPage","measuredTime":"00:00:00.0006669"},"hdr":{"level":"Information","timestamp":"2017-03-17T15:00:55.3022117Z","lineNum":0,"loc":"Store","locId":"0466","ip":"10.111.11.7","hostName":"K-W10ME-3727099","macaddress":"00-15-7E-GE-D2-11","eventid":0,"appVersion":"16.2.0","appName":"L"},"ver":"0.1"}
"""#
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