Donald Shahini
Donald Shahini

Reputation: 925

Regex to match image id from url

I have a URL as follow:

https://res.cloudinary.com/frivillighet-norge/image/upload/v1501681528/5648f10ae4b09f27e34dd22a.jpg

and I want to match only the id of the picture at the end of the string without including .jpg. So far, I have written something like that: ^[A-Za-z0-9]{24}$ which matches a string of numbers and letters with a length of 24, since my id in the string has always length 24, but this does not work as it matches strings of length 24 only.

Any help would be appreciated.

Upvotes: 0

Views: 903

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

You could make the pattern a bit more specific by matching the protocol followed by matching 1+ occurrences of a non whitespace char \S+.

Then match the last occurrence of / and capture the id which consists of 24 characters ([A-Za-z0-9]{24}) followed by matching a dot and 2 or more times a char a-z \.[a-z]{2,}

If you want to match the whole string, you could add anchors to assert the start ^ and end $ of the string.

The id is in capture group 1.

^https?:\/\/\S+\/([A-Za-z0-9]{24})\.[a-z]{2,}$

Regex demo

const regex = /https?:\/\/\S+\/([A-Za-z0-9]{24})\.\w+$/;
const str = `https://res.cloudinary.com/frivillighet-norge/image/upload/v1501681528/5648f10ae4b09f27e34dd22a.jpg`;

console.log(str.match(regex)[1])

Upvotes: 1

Jacob
Jacob

Reputation: 155

[A-Za-z0-9]{24}(?=(\.jpg))

"(?=(.jpg))" is a lookaround. It ends the match with .jpg but does not include it.

Upvotes: 2

Related Questions