Search code examples
regexregular-language

Regex matching needs to stop at first occurrence of file extension and ignore rest


I am trying to build a regex query that would look for image files and would ignore looking into sub directories.

Check the following strings

/content/dam/dev-img-test-folder/huehuehue.gif/jcr:content/renditions/cq5dam.thumbnail.140.100.png

/content/dam/someotherdirectory/nonoono.gif/jcr:content/renditions/cq5dam.thumbnail.140.100.png


/content/dam/dev-img-test-folder/huehuehue.jpg
/content/dam/some-directory/nononoono.jpg

The regex should detect only the last two strings. I tried with /content/dam.*.(jpg|JPG|png), but that gets all four of them.

Can someone guide me to right directions here? Thank you.


Solution

  • /content/dam/[^/]*/[^/]*(jpg|JPG|png)$ will match all files ending (due to $) with jpg|JPG|png in any subdir of dam.

    If you are looking for variable number of subdirs it would be a different regex.

    .*\.(jpg|JPG|png)$ should match any line ending with jpg|JPG|png.

    /([^/]*/){2,5}[^/]*(jpg|JPG|png)$ will match any file 2 to 5 subdirs deep. You might need to escape parenthesis depending on regex engine/syntax.