Open
Description
macOS X 13.1 (22C65)
Xcode Version 14.1 (14B47b)
The following code that uses a Regex Builder will crash at runtime when the user tries to get the result of an optional capture group via the regex match subscript. The same regex using a regex literal successfully returns an optional (but nil) value. You can generate the result builder from the literal if needed.
import Foundation
import RegexBuilder
// Case 1 - using regex literals. Works
let regex1 = #/\s*(?<label>\w+:)?/#
guard let match1 = "NOP".firstMatch(of: regex1) else {
fatalError()
}
print(match1.output.label) // Should be nil. Is nil!
// #######################
// Case 2 - using regex builder. Crashes.
let label = Reference(Substring.self)
let regex2 = Regex {
ZeroOrMore(.whitespace)
Optionally {
Capture(as: label) {
Regex {
OneOrMore(.word)
":"
}
}
}
}
guard let match2 = "NOP".firstMatch(of: regex2) else {
fatalError()
}
print(match2[label]) // Should be nil. Crashes with "Could not cast value of type 'Swift.Optional<Swift.Substring>' (0x....) to 'Swift.Substring' (0x....)."