Home > Software design >  Return the first instance of image name string using regex expression
Return the first instance of image name string using regex expression

Time:09-21

I am trying to form a regex for below lines so that it returns the name of the image. I have multiple image formats. The image formats that it has to return are jpg, png, PNG, jpeg, JPG.

For example, for the first line it should return me, the image's name -- test-hire-logo.png. I've tried below regex , but it will only matches png type only.

([^\/] )\.(png) 
/content/dam/thesis/company-png/test-hire-logo.png.imgw.850.x.jpg
/content/dam/thesis/company/instance-hire-logo.jpg
/content/dam/thesis/company/testing hire.jpg

CodePudding user response:

If you are using PCRE for example, you can make use of \K

.*\/\K[^\/\n] ?\.(?:png|jpg)\b

Explanation

  • .* Optionally match any character except newlines
  • \/\K Match / then then forget what is matched so far
  • [^\/\n] ? Match 1 chars other than / or a newline, as few as possible (non greedy)
  • \.(?:png|jpg) Match .png or .jpg
  • \b A word boundary to prevent a partial word match

Regex demo

Or using a capture group (and if necessary not matching / until the end of the string)

^.*\/([^\/\n] ?\.(?:png|jpg))\b[^\n\/]*$

Regex demo

Note that if it is possible to use a different delimiter than / for the pattern, you don't have to escape the forward slash in the regex.

  • Related