import Foundation
let pattern = #"box(?!-shadow) "#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
positive lookahead
box(?=-shadow)
https://youtu.be/aIEjh0YsxWA?t=309
// select box only if what comes after it IS -shadow
box-sizing
shape-shadow
------------------------------------------------------------------
negative lookahead
box(?!-shadow)
// select box only if what comes after it IS NOT shadow
box-sizing
shape-shadow
------------------------------------------------------------------
negative look behind
(?<!jeffery).+
https://youtu.be/aIEjh0YsxWA?t=212
// this string cannot come before the @
jeffrey@envato.com
joe@envato.com
------------------------------------------------------------------
positive look behind
(?<=box-)sizing
https://youtu.be/aIEjh0YsxWA?t=337
// only want to select 'sizing' if what comes before it is 'box'
// select sizing as long as what comes before it is 'box'
box-sizing
shape-sizing
------------------------------------------------------------------
negative look behind
(?<!box-)sizing
// anything can come before it except 'box'
box-sizing
shape-sizing
-----------------------------------------------------------------
positive lookahead
@.+(?=\.[a-z]{2,4})
// Matches a group after your main expression without including it in the result
wilson@gmail.com
frank@france.fr
joe@paris.france
"""#
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