import Foundation
let pattern = #"^.+version(.*) character file\.([\n\r]+)(\d+)([^\(]+) \([^\d]+( \d+),.+\n\s+.+as a(.+) on.+\n\s+(?:Was.+One\.\n)?((?:.|\n)+[!.])\n(?:.|\n)+\((\d+)(?:.|\n)+$"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
Dungeon Crawl Stone Soup version 0.16-a0-3667-g690a316 (webtiles) character file.
462 8Escape the Ruffian (level 6, -2/47 HPs)
Began as a Bearkin Transmuter on Jan 31, 2015.
Slain by an orc
... wielding a +0 trident
(3 damage)
... on level 4 of the Dungeon.
The game lasted 00:28:53 (3698 turns).
8Escape the Ruffian (Bearkin Transmuter) Turns: 3698, Time: 00:28:53
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"Version:$1\nScore: $3\nName:$4\nCharacter:$6\nLevel:$5\nCause of Death/Victory: $7\nTurns: $8"#
let lookupRange = (testString as NSString).range(of: pattern, options: .regularExpression, range: stringRange)
if lookupRange.intersection(stringRange) != nil {
let result = regex.stringByReplacingMatches(in: testString, range: lookupRange, withTemplate: substitutionString)
print(result)
} else {
print("No matches were found.")
}
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