How to extend regex to accept @ in image urls

Tags: , ,



I have a regex for validating image urls, however some of the images are using @ for example: https://test.com/image-name@2x.jpeg.

How can I extend this regex to accept also the @ character inside of the image link?

Current regex look like this

(http(s?):)([/|.|w|s|-])*.(?:jpg|jpeg|gif|png)

Answer

If it can only be part of the image name, you can add a forward slash followed by matching the allowed chars including the @ before the last dot before the extension.

You can use a character class for the single chars instead of a grouping structure to match one of the listed characters.

If you don’t need the capturing groups, you can omit them to get a match only.

https?://[/.ws-]+/[w@-]+.(?:jpe?g|gif|png)

Regex demo



Source: stackoverflow