let capitals: CharacterClass = "A"..."Z"
let delimiters: CharacterClass = .anyOf("_")
let reference = Reference<Substring>()
let regex = Regex {
ChoiceOf {
Capture(as: reference) {
OneOrMore(delimiters)
}
OneOrMore(capitals)
}
}
"AbCdE_f_G__h".matches(of: regex).forEach { match in
print(match.output)
print(match[reference])
}
This should be a type-safe way to obtain the optional value for the reference, but it crashes in runtime with:
Could not cast value of type 'Swift.Optional<Swift.Substring>' (0x1ec721a10) to 'Swift.Substring' (0x1f0401450).
If I change the reference to let reference = Reference<Substring?>()
it ends with a compile-time error:
Initializer 'init(as:_:)' requires the types 'Substring?' and 'Regex<OneOrMore<Substring>.RegexOutput>.RegexOutput' (aka 'Substring') be equivalent
Shouldn't the compile require such captures to use an optional type?
Otherwise, the compile-time type-safety is compromised.
Is there a way to make it work with RegexBuilder?
I can easily make it work the usual way and still type-safe!
let regex = try! Regex("[A-Z]+|(?<delimiters>[_]+)", as: (Substring, delimiters: Substring?).self)
"AbCdE_f_G__h".matches(of: regex).forEach { match in
print(type(of: match.output.delimiters))
print(match.output.delimiters)
}
where match.output.delimiters
is Optional<Substring>