regex

Regex to get a filename from a url


I am trying to write a regex to get the filename from a url if it exists.

This is what I have so far:

(?:[^/][\d\w\.]+)+$

So from the url http://www.foo.com/bar/baz/filename.jpg, I should match filename.jpg

Unfortunately, I match anything after the last /.

How can I tighten it up so it only grabs it if it looks like a filename?


Solution

  • Non Pcre

    (?:[^/][\d\w\.]+)$(?<=\.\w{3,4})
    

    Pcre

    (?:[^/][\d\w\.]+)$(?<=(?:.jpg)|(?:.pdf)|(?:.gif)|(?:.jpeg)|(more_extension))
    

    Demo

    Since you test using regexpal.com that is based on javascript(doesnt support lookbehind), try this instead

    (?=\w+\.\w{3,4}$).+