Hello people, so, i have some kind of intern urls: for example "/img/pic/Image1.jpg" or "/pic/Image1.jpg" or just "Image1.jpg", and i need to match this "Image1.jpg" in other words i want to match last character sequence after / or if there are no / than just character sequence. Thank you in advance!
The following expression would do the trick:
/([\w\d._-]*)$
Or even easier (but i think this has also been posted below before me)
([^/]+)$
Something like .*/(.*)$ (details depend on whether we're talking about Perl, or some other dialect of regular expressions)
First .* matches everything (including slashes). Then there's one slash, then there's .* that matches everything from that slash to the end (that is $).
The * operates greedily from left to right, which means that when you have multiple slashes, the first .* will match all but the last one.
.*/(.*)
won't work if there are no /s.
([^/]*)$
should work whether there are or aren't.
In Ruby You would write
([^\/]*)$
Regexps in Ruby are quite universal and You can test them live here: http://rubular.com/
By the way: maybe there is other solution that not involves regexps? E.g File.basenam(path)
(Ruby again)
Edit: profjim has posted it earlier.
I noticed you said in your comments you're using javascript. You don't actually need a regex for this and I always think it's nice to have an alternative to using regex.
var str = "/pic/Image1.jpg";
str.split("/").pop();
// example:
alert("/pic/Image1.jpg".split("/").pop()); // alerts "Image1.jpg"
alert("Image2.jpg".split("/").pop()); // alerts "Image2.jpg"
Actually you don't need regexp for this.
s="this/is/a/test"
s.substr(s.lastIndexOf("/")+1)
=> test
and it actually works fine for strings without any /
because then lastIndexOf returns -1.
s="hest"
s.substr(s.lastIndexOf("/")+1)
=> hest