Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate a filename

Tags:

java

regex

file

I need to validate a in a method like this.

    validateFileName(Editable s) {
        String filtered_str = s.toString();
        if (filtered_str.matches(".*[regexp].*")) {
            filtered_str = filtered_str.replaceAll("[regxp]", "");
            s.clear();
            s.append(filtered_str);}

Which regexps should i use to exclude all illegal characters and white-spaces? I'm using linux

like image 749
Binoy Babu Avatar asked Apr 25 '12 21:04

Binoy Babu


2 Answers

If you're using a POSIX-compliant operating system, the legal characters in a file name are a-z, A-Z, 0-9, period, underscore, and hyphen. The regex to match 'illegal' characters would therefore be

[^-_.A-Za-z0-9]

Addendum: This is if you want a fully-portable file name. As I was corrected in Josip's comment below, POSIX itself actually allows more characters.

like image 144
Anachronist Avatar answered Oct 19 '22 09:10

Anachronist


If your idea is only to exclude ilegal and space char you can use something like:

'^[^*&%\s]+$'

where you can add any "ilegal" char into the list of chars (in this case it ignores *, &, % and space) \s is the space! The ^ inside the [] is part of the regex syntax it means: do not match any chars inside [].

like image 20
Gustavo Vargas Avatar answered Oct 19 '22 09:10

Gustavo Vargas