Regex failing for optional group

The following code throws an error:

let string = "1.2"
let regex = /^([0-9]+\.[0-9]+)(-[0-9A-Za-z]+)?/

let match = try regex.firstMatch(in: string)

Error
Regex.Match optional storedCapture contains no some

It works using NSRegularExpression:

let string = "1.2"
let nsRegex = try NSRegularExpression(pattern: "^([0-9]+\\.[0-9]+)(-[0-9A-Za-z]+)?")
let nsFirstMatch = nsRegex.firstMatch(in: string, range: NSRange(location: 0, length: string.count))
if let nsRange = nsFirstMatch?.range(at: 1),
   let range = Range(nsRange, in: string)  {
    string[range]
}

Am I getting something wrong with literal Regex?

Where are you testing this?

On my Mac (Xcode 16.0 on macOS 14.6.1) this program:

func main() throws {
    let string = "1.2"
    let regex = /^([0-9]+\.[0-9]+)(-[0-9A-Za-z]+)?/

    let match = try regex.firstMatch(in: string)
    print(match?.output)
}

try main()

prints:

Optional(("1.2", "1.2", nil))

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

Im testing it in a playground.
Interesting, my test end at the match = try ...
I did not try to print it.

It does work :person_facepalming:t2:
This error banner is somewhat misleading tho

Thanks!!

2 Likes

Yeah. Playgrounds are fun and all, but if you see weird stuff it’s always worth reproducing in a tool.

Also note how my tool has a main() function. That another bit of hard-won experience. Top-level declarations have semantics that are a trap for the unwary, so I always put my tests within a function.

Anyway, please do file a bug (with Apple) about the playground weirdness.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple