import Foundation
let pattern = ##"^(?<rgb>rgb\((?<red>\d{1,3}),\s*\d{1,3},\s*\d{1,3}\))$|^(?<rgba>rgba\(\d{1,3},\s*\d{1,3},\s*\d{1,3},\s*[01](\.\d{1,2})?\))$|^(?<hsla>hsla\(\d{1,3},\s*\d{1,3}%,\s*\d{1,3}%,\s*[01](\.\d{1,2})?\))$|^(?<hsl>hsl\(\d{1,3},\s*\d{1,3}%,\s*\d{1,3}%\))$|^(?<hex>#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})(\d{2})?)$|^(?<cmyk>cmyk\(\d{1,3}%,\s*\d{1,3}%,\s*\d{1,3}%,\s*\d{1,3}%\))$"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
rgb(255,255,255)
rgb(1,23,255)
rgb(132,21,35)
rgba(255,255,255,0.4)
rgba(1,23,255,0.3)
rgba(1,23,255,1)
rgba(1,23,255,1.0)
rgba(132,21,35,0.7)
#403238
#ff323890
#ff890
#FF323890
hsl(240, 100%, 50%)
hsl(248, 53%, 58%)
hsl(147, 50%, 47%)
hsla(9, 100%, 64%, 0.6)
hsla(9, 100%, 64%, 0.8)
hsla(9, 100%, 64%, 0.8)
cmyk(0%, 100%, 100%, 0%)
cmyk(0%,46%,51%,37%)
// should fail
rgba(255,255,255)
rgba(1,23,255)
rgba(132,21,35)
rgba(1,23,255,0.)
hsla(240, 100%, 50%)
hsla(248, 53%, 58%)
hsla(147, 50%, 47%)
rgb(255,255,255,0.4)
rgb(1,23,255,0.13)
rgb(132,21,35,0.14)
hsl(9, 100%, 64%, 0.6)
hsl(9, 100%, 64%, 0.8)
hsl(9, 100%, 64%, 0.8)
#FG323890
#ars90
"""##
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