import Foundation
let pattern = #"(\[\d{3,5} ?x ?\d{3,5}\])"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
Should match:
Hey guys check out this awesome hi-def picture! [320x480]
[F]irst time here plz be nice [6969x6969]
Spaces around the x [123 x 456]
herp derp durr (smallest dimensions that will match) [100x100]
Check out this massive 2.1 jiggapixel image of the entire USA in high detail! (highest dimensions that will match) [99999x99999]
Should not match:
Please go to this spammy site and buy shit so we can steal your credit card (no tag)
Letters in the tag [i234x5678]
Dimension too small [99 x 123]
Dimension too big [100000 x 123]
Wrong bracket {123 x 456]
"""#
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