import Foundation
// WARNING: You included a flag that Swift doesn't support: u
// When this flag is set, it makes the pattern and subject strings to be treated as unicode.
// Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.
let pattern = ##"""
# Start defining
(?(DEFINE)
(?<XSEP>\s*[xх\*\-\s]?\s*)
(?<MARGIN>(?:\.\d)?)
(?<RADIUS>r?[12]\d(?&MARGIN))
(?<J>(?:1[01]|[4-9])(?&MARGIN)j?)
(?<DIAM>
\b
(?:
(?&RADIUS)(?:\s*\/\s*(?&J))?
|
(?&J)(?&XSEP)(?&RADIUS)
)
\b
)
(?<PCD>\b(?:[pb]cd\s*)?[34568](?&XSEP)(?:98|[12]\d{2})(?&MARGIN)\b)
(?<ET>(?:(?:et|ет)\s*)?\-?\d+(?&MARGIN)\b)
(?<CB>\b(?:(?:цо|cb|d(?:ia)?)\s*)?\d{2,3}(?&MARGIN)\b)
)
# End defining
(?:
(?<diam>(?&DIAM))
|
(?<pcd>(?&PCD))
|
(?<et>(?&ET))
|
(?<cb>(?&CB))
)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .allowCommentsAndWhitespace, .dotMatchesLineSeparators])
let testString = #"""
r22 pcd 4x108 ET 45.5 ЦО 58.5
15 /5.0j 6*108 et45 ЦО 58.5
15/ 5.0j 4x108 -45.5 58.5
pcd 4x138 15/5.0j ET58.5 ЦО45
ЦО45.5 ET58.5 19 pcd 4x 108
r15/5.6j pcd 5х112 ET60 CB66
et50 r15/5 5х112 ET60 d66
r15/5 pcd 5*112 ET60 dia 66
5.6j x 15.5 pcd 5 х 112 ет -60 CB66
5x15.5 5х112.5 ET60 CB66
250/50 r16
"""#
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