Skip to content

Java RegEx – Validate File Name & Extension

Java RegEx – Validate File Name & Extension example shows how to validate a file name along with the file extension using Java regex pattern.

How to validate a file name in Java using regex?

File name validation can be done by writing an appropriate regex pattern according to the file name requirements you have. For the purpose of this example, let’s assume that the file name may contain only letters, numbers, hyphens (“-“),  underscores, dots (“.”), and spaces.

For the extension part, the file name must have one of these extensions (doc, pdf, csv, and xls).

Here is the pattern for these requirements.

Where,

Let’s try this pattern with some of the sample file names we want to validate.

Output

The first file name contains an exclamation mark (!) that is not allowed so it fails, the second file name does not have the required extension so it fails as well.

The third file name does not have an extension, similarly, the fourth file name only has an extension so both of them fail in the validation. The rest of the file names passed the regex validation as they fulfill all the criteria.

You can add or remove any character you want to allow or disallow in the regex to fit your needs.

Important note: Many operating systems treat file names with the only extension as a valid one. In that case, you can replace the “+” with “*” to allow file names with only extensions as given below.

The “+” matches one or more times, while the “*” matches with zero or more. So even if any of the allowed characters are absent before the dot “.”, the pattern will still match.

If you want to learn more about the regex, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

We are on YouTube!

Leave a Reply

Your email address will not be published.