Your current issue is that \w only matches letters, numbers and the underscore, but not dashes. You can say “match everything \w matches as well as these other characters” by putting it inside a character class: [\w-].

Your next issue will be that you forgot to escape your periods, so your regex as it stands will match be_a_hippy/smoke_pot. You want to write (\.txt|\.doc|\.pdf|\.vsd|\.xls|\.xlt|\.dot|\.pot|\.ppt|\.mpp).

Well, actually, you don’t want to write that, you want to write \.(txt|doc|pdf|vsd|xls|xlt|dot|pot|ppt|mpp).

And (outside the fact that this also constitutes a microoptimisation) I’d want to group someone of those, using character classes, because they belong to the same application: \.(txt|do[ct]|pdf|vsd|xl[st]|p[op]t|mpp).

Which brings us to

$abspath =~ m{ / [\w-]+ \.(txt|do[ct]|pdf|vsd|xl[st]|.p[op]t|mpp) \z } +msx;

I used \z, because that means end-of-string, whereas $ means end-of-string plus a variety of subtly different things. I also took the liberty of using the m// syntax instead of an unadorned // so that I could use delimiters other than the / – that way the / inside the regex needn’t be escaped. I took the additional liberty of adding /x so that whitespace inside the regex becomes insignificant – then you can use spacing, linebreaks and the like to structure the regex. Lastly, on TheDamnian’s suggestion from Perl Best Practices, I always also add /m and /s to my patterns out of habit.

Makeshifts last the longest.


In reply to Re: regular expression on filenames with absolute path by Aristotle
in thread regular expression on filenames with absolute path by ramthen

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.