wreckingcode wreckingcode - 1 year ago 73
Swift Question

Retrieve string between two special characters

I have an image URL which I need to extract the UUID from. The URL is formed like so:


This URL points to the image in my bucket, where its name format is
. I need to obtain this UUID in order to delete it so it doesn't take up space when the user uploads a new image (which replaces the existing one).

I tried testing this here with the following regex:
Essentially, I want to extract all the text between a
and a period (
), which is where the UUID is (
). It successfully matched the pattern I wanted (under "match information")...well, including the
which is actually an escaped slash.

However, when using it in Swift, it's actually matching the characters including and after the first
(output is
). I've tried this:

let regex = Regex("%([A-Z0-9-]+).")

if let match = regex.match(self.existingItem.photoURL) {

Side note: I'm using this Regex framework.

Can anyone please shed some insight on why this happens in Swift and how to fix it?

Answer Source

You need the Capture:

let reg = Regex("%2F([A-Z0-9-]+)[.]")

if let res = reg.match(self.existingItem.photoURL)?.captures[0] {

Note that the (...) creates a capture group that is used to get smaller substrings from your matches.

Judging by the Sharplet Regex Github page, capture group indexing starts with 0, so the first capture group can be accessed via 0 index.