Nirpeksh :
I have a string where I want to remove all special characters except hyphen , a dot and space.
I am using filename.replaceAll("[^a-zA-Z0-9.-]","")
. It is working for .
and -
but not for space.
What should I add to this to make it work for space as well?
Karol Dowbecki :
Use either \s
or simply a space character as explained in the
Pattern
class javadoc
\s - A whitespace character: [ \t\n\x0B\f\r]
- Literal space character
You must either escape -
character as \-
so it won't be interpreted as range expression or make sure it stays as the last regex character. Putting it all together:
filename.replaceAll("[^a-zA-Z0-9\\s.-]", "")
filename.replaceAll("[^a-zA-Z0-9 .-]", "")