I’ve seen other posts on SO for RegEx matches excluding strings (using negative look ahead / look behind) but i’m still having a hard time getting it to work. Was hoping someone could help.
I have a RegEx
\.(gif|jpg|png)$
Which i use to match any filenames ending in (gif/jpg/png)
However i want to use an exclusion list so that certain file names will not be matched.
eg
- match any http://example.com/images/filename.jpg / gif / png
- except (http://example.com/images/foo.jpg, http://example.com/images/foo.gif, http://example.com/images/foo.png) (http://example.com/images/bar.jpg, http://example.com/images/bar.gif, http://example.com/images/bar.png)
Thanks very much!
If the number of exclusions is low, you can use multiple negative look-behinds like this:
The ‘/’ before foo and bar makes sure the full name matches foo or bar, it doesn’t only end in it. If it is possible that there is no ‘/’ before the filename, you need to adjust this part.
One drawback of look-behinds is that you can only use a defined length, so no
*,+or{1,5}is allowed. You have to specify every exception by itself.Note that look-arounds don’t change the ‘position’ in the string from which it is looked at, which is why you can concatenate them like that.