import Foundation
let pattern = #"(?<timestamp>^.{19})\s\S+\s\S+\s(?<method>\S+)\s(?<w_path>\S*\/)(?<file>\S*)\s(?<var>\S+?)(\s|(\|.+\|)(?<error>\S+)\s)(?<dport>\S+)\s\S\s(?<sip>\S+)\s(?<agent>\S+)\s(?<status>\S+).+"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
2011-01-12 15:42:36 W3SVC1499154376 123.45.48.11 GET /main/view.asp - 80 - 210.177.175.190 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+6.0) 200 0 0
2011-01-12 15:42:36 W3SVC1499154376 123.45.48.11 GET /main/viewasp - 80 - 210.177.175.190 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+6.0) 200 0 0
2011-01-12 15:42:36 W3SVC1499154376 123.45.48.11 GET /view.asp cate_id=2&vod_id=784 80 - 210.177.175.190 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+6.0) 200 0 0
2011-01-12 15:42:36 W3SVC1499154376 123.45.48.11 GET / - 80 - 210.177.175.190 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+6.0) 200 0 0
2011-01-12 15:42:36 W3SVC1499154376 123.45.48.11 GET /view.asp cate_id=2&vod_id=784%20and%200%3C(select%20top%201%20cast([name]%20as%20nvarchar(256))%2bchar(94)%20from(select%20top%20%201%20dbid,name%20from%20[master].[dbo].[sysdatabases]%20order%20by%20[dbid])%20t%20order%20by%20[dbid]%20desc)--|107|80040e14|'('_근처의_구문이_잘못되었습니다. 80 - 210.177.175.190 pangolin/2.0 500 0 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