kokoko
kokoko

Reputation: 25

How can I change the invalid characters to valid chars in Java?

 private static void isValidName(String[] filename){
    FileSystem fs  = FileSystems.getDefault();
    System.out.println(fs);

    String pattern = ("^[\\w&[^?\\\\/. ]]+?\\.*[\\w&[^?\\\\/. ]]+$");               

    for (String s: filename) {
        //System.out.println(s.matches(pattern));
        if (s.matches(pattern)==false){

            System.out.println(s.matches(pattern));

        }
    }

Now I call this function:

 String[] name2={"valami.txt."};
 isValidName(name2);

How can I replace the invalid characters in if(s.matches(pattern)==false) with valid characters?

Output: false

Upvotes: 1

Views: 1782

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You may use this piece of code to remove/replace invalid characters:

String[] bad = {
     "foo.tar.gz",
     " foo.txt",
     "foo?",
     "foo/",
     "foo\\",
     ".foo",
     "foo."
   };
  String remove_pattern = "^[ .]+|\\.+$|\\.(?=[^.]*\\.[^.]*$)|[?\\\\/:;]"; 
  for (String s: bad) {
       System.out.println(s.replaceAll(remove_pattern, "_"));
  }

See IDEONE demo

Output:

foo_tar.gz
_foo.txt
foo_
foo_
foo_
_foo
foo_

REGEX contains several alternatives joined with | alternation operator to match the invalid character(s) only.

  • ^[ .]+ - Matches 1 or more leading spaces or dots
  • \\.+$ - Matches final ., 1 or more occurrences (change to [. ]+$ if you plan to also replace trailing spaces)
  • \\.(?=[^.]*\\.[^.]*$) - Matches a . that is followed by an optional number of characters and another dot (thus, leaving the last dot in the string)
  • [?\\\\/:;] - Matches ?, \, /, : and ; literally.

Upvotes: 2

Related Questions