import Foundation
let pattern = #"<b>(.*?)<\/b>"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .dotMatchesLineSeparators])
let testString = #"""
<b> GALADRIEL (V.O.)
</b> (Elvish: subtitled)
"I amar prestar sen: han mathon ne nen,
han mathon ne chae...a han noston ned
wilith."
(English:)
The world is changed: I feel it in the
water, I feel it in the earth, I smell it
in the air...Much that once was is lost,
for none now live who remember it.
<b>SUPER: THE LORD OF THE RINGS
</b>
<b>EXT. PROLOGUE -- DAY
</b>
IMAGE: FLICKERING FIRELIGHT. The NOLDORIN FORGE in EREGION.
MOLTEN GOLD POURS from the lip of an IRON LADLE.
<b> GALADRIEL (V.O.)
</b> It began with the forging of the Great
Rings.
IMAGE: THREE RINGS, each set with a single GEM, are received
by the HIGH ELVES-GALADRIEL, GIL-GALAD and CIRDAN.
<b> GALADRIEL (V.O.) (CONT'D)
</b> Three were given to the Elves, immortal,
wisest...fairest of all beings.
IMAGE: SEVEN RINGS held aloft in triumph by the DWARF LORDS.
<b> GALADRIEL (V.O.) (CONT'D)
</b> Seven to the Dwarf Lords, great miners
and craftsmen of the mountain halls.
IMAGE: NINE RINGS clutched tightly by the KINGS OF MEN...as
if holding-close a precious secret.
<b> GALADRIEL (V.O.) (CONT'D)
</b> And Nine...nine rings were gifted to the
race of Men who, above all else, desire
power.
<b> (MORE)
</b>
"""#
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