import Foundation
let pattern = #"(\S+).*\"*(?:GET|POST|HEAD).* (MJ12bot|Baiduspider|AhrefsBot|UptimeRobot).*""#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
69.162.111.222 - - [07/Feb/2017:15:54:14 +0200] "HEAD / HTTP/1.1" 200 296 "http://dummydomain.nl/" "Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/)"
185.119.111.222 - - [07/Feb/2017:15:55:37 +0200] "GET /wp-login.php HTTP/1.1" 200 2860 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
185.119.111.222 - - [07/Feb/2017:15:55:37 +0200] "POST /wp-login.php HTTP/1.1" 200 3610 "http://www.dummydomain.nl/wp-login.php" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
149.210.111.222 - - [07/Feb/2017:15:59:13 +0200] "POST /wp-cron.php?doing_wp_cron=1496930353.4784278869628906250000 HTTP/1.1" 200 181 "http://www.dummydomain.nl/wp-cron.php?doing_wp_cron=1496930353.4784278869628906250000" "WordPress/4.7.5; http://www.dummydomain.nl"
69.162.111.222 - - [07/Feb/2017:15:59:12 +0200] "HEAD / HTTP/1.1" 301 229 "http://dummydomain.nl/" "Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/)"
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
if let firstMatch = regex.firstMatch(in: testString, range: stringRange) {
let result: [String] = (1 ..< firstMatch.numberOfRanges).map { (testString as NSString).substring(with: firstMatch.range(at: $0)) }
print(result)
} else {
print("No matches were found.")
}
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