Replacing illegal character in fileName

北城以北 提交于 2020-07-14 16:37:21

问题


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

I tried following code: But this did not worked!

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

回答1:


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

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("[\\\\/:*?\"<>|]", "_");



回答3:


Keep it simple.

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

http://ideone.com/TINsr4




回答4:


Even simpler

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

Predefined Character Classes:

  • \w A word character: [a-zA-Z_0-9]



回答5:


I know there have been some answers here already, but I would like to point out that I had to alter the given suggestions slightly.

filename.matches("^.*[^a-zA-Z0-9._-].*$")

This is what I had to use for .matches in Java to get the desired results. I am not sure if this is 100% correct, but this is how it worked for me, it would return true if it encountered any character other than a-z A-Z 0-9 (.) (_) and (-).

I would like to know if there are any flaws with my logic here.

In previous answers I've seen some discussion of what should or should not be escaped. For this example, I've gotten away without escaping anything, but you should escape the (-) minus character to be safe as it will "break" your expression unless it is at the end of the list. The (.) dot character doesn't have to be escaped within the ([]) Square Braces it would seem, but it will not hurt you if you do escape it.

Please see Java Patterns for more details.




回答6:


If you want to use more than like [A-Za-z0-9], then check MS Naming Conventions, and dont forget to filter out "...Characters whose integer representations are in the range from 1 through 31,...".




回答7:


for NodeJS (v10), the function replaceAll() is undefined!

The solution is:

let newName = myString.replace(/[^a-zA-Z0-9.-]/gi, "_");


来源:https://stackoverflow.com/questions/15075890/replacing-illegal-character-in-filename

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!