Regular Expression To Match Valid Filename

A regular expression to match valid filenames. It can be used to validate filenames entered by a user of an application, or the filename of files uploaded from a scanner.

The expression ensures that your filename conforms to specific rules, including no leading or trailing spaces and no use of any characters besides the letters A-Z and numbers 0-9.

/^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9_-]+$/


  • regex.txt
  • 1.2
  • patten.exe


  • .htaccess
  • &.jpg
  • 你好.py

See Also: