The second bracket part of your regex just needs some additions: [a-zA-Z0-9-._]
Basically add any additional characters at the end after the ranges.
Emacs
A community for the timeless and infinitely powerful editor. Want to see what Emacs is capable of?!
Get Emacs
Rules
- Posts should be emacs related
- Be kind please
- Yes, we already know: Google results for "emacs" and "vi" link to each other. We good.
Emacs Resources
Emacs Tutorials
- Beginner’s Guide to Emacs
- Absolute Beginner's Guide to Emacs
- How to Learn Emacs: A Hand-drawn One-pager for Beginners
Useful Emacs configuration files and distributions
Quick pain-saver tip
Elisp regular expressions are case insensitive by default, so they should match uppercase letters too.
To just add a dash, you could simply put that into the second group. So [a-z0-9-]
, you don’t have to escape it because it can’t be a range operator if it’s at the end of the group. The same goes for any other character you want to match.
You could also use [\\w. _-]
(notice the literal space between the dot and the underscore). The \w
is a shorthand for A-Za-z0-9
. This should match all valid filenames as long as they don’t contain letters with diacritics.
On a POSIX filesystem (MacOS, Linux, BSD, etc.), any character except '/' can be part of a filename. So why are you limiting yourself to a couple of punctuation characters? The best regex to match filenames is: "[^/]+"
If you're using Windows, it gets a bit trickier, but for reading the filesystem, "[^/\\\\]+" seems like it should be adequate. If you want to make sure you can create a filename on Windows, you'd have to exclude a few more characters. Nevertheless, excluding invalid characters still seems like a better approach than trying to include all the valid ones.