I have code like this …
func blah() {
if let r = someString.firstMatch(of: /([abc])(\d{2})$/) {
blah blah .. String(r.1), String(r.2)
}
}
Normally with a regex, i’d just keep the regex-guts as a variable.
Hence, something like this:
let RX: RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
I have completely and absolutely failed to be able to do this, and have searched for hours.
some suggest you need any RegexComponent
let RX: any RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
But it simply doesn’t work.
the argument of firstMatch#of
is undoubtedly a RegexComponent
.
How the heck can I make/set a variable that is a RegexComponent
??
>Solution :
This should do the trick:
let RX = /([abc])(\d{2})$/
Now, since it works, you can Alt+click on the var name (RX
), and the type inference (ie, type of the variable "deduced" by the compiler) should tell you it’s a Regex<Substring>
So you can write also:
let RX: Regex<Substring> = /([abc])(\d{2})$/
I don’t have the full explanation, since I haven’t played with the new Regex
, but I guess it’s because RegexComponent
is protocol
, so there is no really an init
, and there must be something with "literals" (or assimilated).