import Foundation
let pattern = #"""
(?>^|\s+|\W)
(
(?>[a-z]\d*|\d+[a-z]?
(?>\(
([a-z]\d*|\d+[a-z]?)
\)[a-z]?
)?)
(?>\.(?>[a-z]|\d+[a-z]?))*
|
(?>M{0,4}(?>CM|CD|D?C{0,3})(?>XC|XL|L?X{0,3})(?>IX|IV|V?I{0,3}))
)
(?>\s+|\W|$)
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
Appendix 1
6.48
CP 198
3.2.4 G
2
1.
B.
Appendix 1
Annex A
4A.10.1 and 4A.15
4A.21.10
Annex ii
A)
SECTION IV
52.19A
PRACTICE DIRECTION 83—
RSC ORDER 109
Rule 4
ADMINISTRATIVE COURT GUIDANCE
PRACTICE STATEMENT
THE PROTOCOL
C.6
Draft modules
CIS11:
Appendix 13(2)e
2002 no.
(a)
L7.3.1.R
(iii)
"""#
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