G'day lirc201,
Welcome to the Monastery.
You've missed some information which could be important. Is there a minimum number of characters? Filenames can't start with [_.-], but can they end with all, some or none of those?
Just this week, I implemented something along these lines for production code. The requirements were: names could be just one character long; the start and end characters (the same character for one-character names) must match [A-Za-z0-9]; the middle characters for names with three or more characters must match [A-Za-z0-9_.-]. The regex for this:
qr{\A[A-Za-z0-9](?:[A-Za-z0-9_.-]*?[A-Za-z0-9]|)\z}
Note that, in a bracketed character class, '.' is not special and '-' is only special when between two characters to form a range: as you can see, you don't actually need to escape any characters.
Here's a limited test:
$ perl -E ' my @x = (qw{A AA AAA _ __ ___ -A A- A.A A. .A A-A A_A}, "A\n", "A\ +tA"); my $re = qr{\A[A-Za-z0-9](?:[A-Za-z0-9_.-]*?[A-Za-z0-9]|)\z}; say "|$_| is ", /$re/ ? "OK" : "BAD" for @x ' |A| is OK |AA| is OK |AAA| is OK |_| is BAD |__| is BAD |___| is BAD |-A| is BAD |A-| is BAD |A.A| is OK |A.| is BAD |.A| is BAD |A-A| is OK |A_A| is OK |A | is BAD |A A| is BAD
Modify that to suit your own filename specifications. Add some more tests which should probably include digits and lowercase letters.
— Ken
In reply to Re: Regex to detect file name
by kcott
in thread Regex to detect file name
by lirc201
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |