简体   繁体   English

如何从字符串中删除除-以外的所有特殊字符。 和空间

[英]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.-]","") . 我正在使用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 使用\\s或仅使用空格字符 as explained in the Pattern class javadoc Pattern类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 .-] 您可以使用此正则表达式[^a-zA-Z0-9\\s.-][^a-zA-Z0-9 .-]

\\s matches whitespace and \\s匹配空格,并且 (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 .-]", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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