Java – Validate file extension using regular expressions

Here we can learn two ways to validate file name extensions in the system using regular expressions:
– Regex matcher method
– String matches method

In these examples, file extensions ‘.txt’ or ‘.xml’ will return ‘true’.
Regular expression used is: .+\\.(?i)(txt|xml)$.
where 
.+             – matches one or more of any character
\.              – followed by a dot
(?i)           – ignores case sensitive check
(txt/xml) – file extensions ‘.txt’ or ‘.xml’
$              – end of line

Example 1 – Regex matcher method

class RegExTest
{
    public static void main( String args[] )
    {
        String[] fileNames = { “file.txt”, “file.xml”, “file-name.txt”, “file_name.txt”, “file.name.txt”,
“file name.txt”, “file.abc”, “file.tmp”, “filetxt.abc”, “file.txt.abc”, “xml”, “.xml”, };
        Pattern pattern = Pattern.compile( “.+\\.(?i)(txt|xml)$” );
        Arrays.stream( fileNames ).forEach( fileName ->
        {
            Matcher matcher = pattern.matcher( fileName );
            System.out.println( fileName + ” – ” + matcher.matches() );
        } );
    }
}

Example 2 – String “matches” method

import java.util.Arrays;
class RegExTest
{
    public static void main( String args[] )
    {
        String[] fileNames = { “file.txt”, “file.xml”, “file-name.txt”, “file_name.txt”, “file.name.txt”,
             “file name.txt”, “file.abc”, “file.tmp”, “filetxt.abc”, “file.txt.abc”, “xml”, “.xml”, };
        Arrays.stream(fileNames).forEach( fileName -> 
       {
             System.out.println( fileName + ” – ” + fileName.matches( “.+\\.(?i)(txt|xml)$” ) );
       } );
}

Output in both cases

file.txt – true
file.xml – true
file-name.txt – true
file_name.txt – true
file.name.txt – true
file name.txt – true
file.abc – false
file.tmp – false
filetxt.abc – false
file.txt.abc – false
xml – false
.xml – false

Leave a Comment

Your email address will not be published. Required fields are marked *