How to Validate File Extensions Using Regular Expression in Java


In following example, you can see how to validate file extensions using regular expression. If you just need to verify that a file matches a certain format, pass in the regular String using the matches() method in the String object.

Source Code

package com.beginner.examples;

public class VerifyFileExample {

	public static void main(String[] args) {

		String reg = "[^\s]+\.(java|txt|class|doc|csv|pdf|html|xml)";

		String file1 = "Example.java";
		String file2 = "notes.txt";
		String file3 = "document.doc";
		String file4 = "test.abc";

		// Verify using the matches() method of the String object
		System.out.println(file1 + " : " + file1.matches(reg));
		
		System.out.println(file2 + " : " + file2.matches(reg));
		
		System.out.println(file3 + " : " + file3.matches(reg));
		
		System.out.println(file4 + " : " + file4.matches(reg));
	}

}

Output:

Example.java : true
notes.txt : true
document.doc : true
test.abc : false
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments