import Foundation
let pattern = ##"""
\b(
# MAC address like xx:xx:xx:xx:xx:xx
[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}
|
# MAC address like xx-xx-xx-xx-xx-xx
[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}
|
# MAC address like xxxx.xxxx.xxxx
[0-9a-f]{4}\.[0-9a-f]{4}\.[0-9a-f]{4}
|
# IPv4 address in dotted-quad format
# Not a lot of value for our needs in checking range of each octet
# Need to be more mindful of performance here anyway.
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
)\b
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
192.168.1.2
10.0.0.0
ff:ff:ff:ff:ff:ff
FF-FF-FF-FF-FF-FF
FFFF.FFFF.FFFF
ffff.ffff.ffff
blah127.0.0.1haha
foo127.0.0.1
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\1"#
let lookupRange = (testString as NSString).range(of: pattern, options: .regularExpression, range: stringRange)
if lookupRange.intersection(stringRange) != nil {
let result = regex.stringByReplacingMatches(in: testString, range: lookupRange, withTemplate: substitutionString)
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