import Foundation
let pattern = #"(?m)^(\d\.?[\d.]*? ?[ \-,:\w]+) ?\r?$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
5.2 Marking this is a heading
All relevant information, as detailed in 5.1, which is to be marked on the equipment, shall be
specified in the relevant product standard.
Markings shall be indelible and easily legible.
Marking of the manufacturer's name or trademark and type designation or serial number is
mandatory on the equipment and preferably on the nameplate, if any, in order to permit the
----------------------------------------------------------------------------------
MARKING this is a heading
70 General this is a subheading
70.1 Industrial control equipment shall be plainly marked with: this is a heading
a) The manufacturer’s name, trademark, or other descriptive marking by which the organization
responsible for the product may be identified – hereinafter referred to as the manufacturer’s
name;
---------------------------------------------------------------------------------
9 Marking this is a heading
Advisory Note: In Canada, there are two official languages, English and French. Annex C lists
acceptable French translations of the markings specified in this standard. All markings required
by this standard may have to be in other languages to conform with the language requirements
where the product is to be used.
9.1 General-purpose marking this is a subheading
In addition to the marking required for general-purpose equipment, the minimum marking shall
include the information in 9.2 through 9.11 as applicable. This information shall be readily visible
9.1.3 this is also a subheading
(?m)^(\d+\.\d+\s[ \w,\-]+)\r?$ <--- headings
(?m)^(\d\.[\d.]+ ?[ \w]+) ?\r?$ <--- subheadings
(?m)^(\d\.?[\d.]*? ?[ \-,:\w]+) ?\r?$ <--- master
"""#
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