Replacing illegal character in fileName

2022-08-31 16:01:29

In Java, I've a File-Name-String. There I want to replace all illegal Characters with '_', but not , , , and a-z0-9-._

I tried following code: But this did not worked!

myString = myString.replaceAll("[\\W][^\\.][^-][^_]", "_");

答案 1

You need to replace everything but . The within the brackets stands for "NOT".[a-zA-Z0-9.-]^

myString = myString.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");

答案 2

If you are looking for options on windows platform then you can try below solution to make use of all valid characters other than "\/:*?"<>|" in file name.

fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");