Replacing illegal character in fileName

后端 未结 7 1973
情书的邮戳
情书的邮戳 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 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.

提交回复
热议问题