Suppose I have a log file that I've split into an array of strings. For example I have these lines here.
123.4.5.1 - - [03/Sep/2013:18:38:48 -0600] "GET /products/car/ HTTP/1.1" 200 3327 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36"
123.4.5.6 - - [03/Sep/2013:18:38:58 -0600] "GET /jobs/ HTTP/1.1" 500 821 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20100101 Firefox/23.0"
I can parse these out with typical string manipulation however I think there is a better way to do it with Regex. I attempted to follow a similar pattern that someone had used in python, but I can't quite figure it out. Here's my attempt.
This is the pattern: ([(\d.)]+) - - [(.?)] "(.?)" (\d+) - "(.?)" "(.?)" when I attempt to use it, I get no matches.
let lines = contents.split(separator: "\n")
let pattern = "([(\\d\\.)]+) - - \\[(.*?)\\] \"(.*?)\" (\\d+) - \"(.*?)\" \"(.*?)\""
let regex = try! NSRegularExpression(pattern: pattern, options: [])
for line in lines {
let range = NSRange(location: 0, length: line.utf16.count)
let parsedData = regex.firstMatch(in: String(line), options: [], range: range)
print(parsedData)
}
If I could extract the data to a model that would be the best. I need to ensure that the code is performant and fast because there could be thousands of lines I should account for.
Expected Result
let someResult = (String, String, String, String, String, String) or
let someObject: LogFile = LogFile(String, String, String...)
I would be looking for the parsed line to be broken up into it's individual parts. IP, OS, OS Version, Browser Browser Version etc.. any real parsing of the data will be sufficient.