I try to think of what defines the thing I'm looking for. In this case, I'd think it's the last thing in the string, and the string is separated by '/' marks, that would give me a regex like this:
$file =~ /\/([^\/]+)$/;
This says, find a '/' followed by one or more non-'/' up until the end of the string. Capture the non-'/' stuff.
Update: More of a breakdown. Because '/' itself is used by perl to delimit the regex, in order to search for a '/' in a string I escape it in the regex, hence '\/'.
The bit that looks like '\/([^\/]+)' is saying find a '/' followed by some non-'/' chars. '\/' means find a '/', '([^\/]+)' means get a bunch of non-'/' chars. '[^\/]' matches any character that isn't a '/'. Putting a '+' at the end of '[^\/]' means match 1 or more times, and putting that inside of parenthesis means capture it for a back reference.
The '$' anchors that to the end of the string.
Once you look at how a regex works, it can be fun to think about strings that could break it. What would $1 look like if $file were any of these?
Another Update: Great point kwaping! (see below) |