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)


In reply to Re: R.Exp. Matching from the Right by pileofrogs
in thread R.Exp. Matching from the Right by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.