Replacing illegal character in fileName

后端 未结 7 1925
情书的邮戳
情书的邮戳 2020-12-24 10:39

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

相关标签:
7条回答
  • 2020-12-24 10:56

    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("[\\\\/:*?\"<>|]", "_");
    
    0 讨论(0)
  • 2020-12-24 11:09

    Even simpler

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

    Predefined Character Classes:

    • \w A word character: [a-zA-Z_0-9]
    0 讨论(0)
  • 2020-12-24 11:13

    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.

    0 讨论(0)
  • 2020-12-24 11:13

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

    The solution is:

    let newName = myString.replace(/[^a-zA-Z0-9.-]/gi, "_");
    
    0 讨论(0)
  • 2020-12-24 11:15

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

    myString = myString.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");
    
    0 讨论(0)
  • 2020-12-24 11:17

    Keep it simple.

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

    http://ideone.com/TINsr4

    0 讨论(0)
提交回复
热议问题