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 | |
|
Re^2: R.Exp. Matching from the Right
by Anonymous Monk on Feb 23, 2006 at 18:10 UTC | |
by ikegami (Patriarch) on Feb 23, 2006 at 18:39 UTC |