in reply to R.Exp. Matching from the Right

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)

Replies are listed 'Best First'.
Re^2: R.Exp. Matching from the Right
by kwaping (Priest) on Feb 23, 2006 at 19:39 UTC
    You can use different delimiters for your match, which removes the need to escape your slashes. This may or may not make that line less confusing. :)
    $file =~ m|/([^/]+)$|;
Re^2: R.Exp. Matching from the Right
by Anonymous Monk on Feb 23, 2006 at 18:10 UTC
    This one worked great, but can you explain a little how it is doing it? Thanks a lot you all!
      It reads as /, followed by one or more characters which aren't /, followed by the end of string. It works because of backtracking. When it can't find a match with the first slash (because there are other slashes between it and the end of string), it tries starting at a different slash. Rinse and repeat until a match is found, or there are no more slashes at which to start.