import Foundation
let pattern = ##"(?P<Hex>(?<=.[^}{])#(?:[\dA-F]{6}|[\dA-F]{3})(?=\W[^}{]))+"##
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let testString = ##"""
#BED
{
color: #FfFdF8; background-color:#aef;
font-size: 123px;
background: -webkit-linear-gradient(top, #f9f9f9, #fff);
}
#Cab
{
background-color: #ABC;
border: 2px dashed #fff;
}
#dddd
Valid Hex Color Codes
#FFF
#025
#F0A1FB
Invalid Hex Color Codes
#fffabg
#abcf
#12365erff
#BED{ color: #FfFdF8; background-color:#aef; font-size: 123px;}#Cab{ background-color: #ABC; border: 2px dashed #fff;}
"""##
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