Test filename with regular expression

This question was asked specifically to allow a three letter extension.

For anyone coming from DuckDuckGo like me (yes, you shouldn't use Google :p), this regex tests for valid filenames and file paths on Windows, Unix and macOS:

^[^<>:;,?"*|/]+$

Note: On Windows, \is not allowed in filenames, but the above regex works for checking valid paths on Windows. Include \\ between the brackets ^[...]+$ if you want it to check for valid filenames and not checking paths.


You could use these expressions instead:

  • \w - is the same as [a-zA-Z0-9_]
  • \d - is the same as [0-9]
  • \. - is the same as [.]{1}

Which would make your regex:

^[\w,\s-]+\.[A-Za-z]{3}$

Note that a literal dash in a character class must be first or last or escaped (I put it last), but you put it in the middle, which incorrectly becomes a range.

Notice that the last [a-zA-Z] can not be replaced by \w because \w includes the underscore character and digits.

EDITED: @tomasz is right! \w == [a-zA-Z0-9_] (confirmed here), so I altered my answer to remove the unnecessary \d from the first character class.

Tags:

Regex