简体   繁体   中英

How to remove all special Characters from a string except - . and space

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?

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 .-]", "")

You can use this regex [^a-zA-Z0-9\\s.-] or [^a-zA-Z0-9 .-]

\\s matches whitespace and (space character) matches only space.

So in this case if you want to match whitespaces use this:

filename.replaceAll("[^a-zA-Z0-9\\s.-]", "");

And if you want only match space use this:

filename.replaceAll("[^a-zA-Z0-9 .-]", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM