java 替换除一个以外的所有特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16887607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all special character except one
提问by ses
string = str.replaceAll("\W", " ")
This replace all special character by " " (space).
这用“”(空格)替换所有特殊字符。
But I try to exclude dash "-" as special character.
但我尝试排除破折号“-”作为特殊字符。
This my try:
这是我的尝试:
string = str.replaceAll("\W[^-]", " ")
But this not that I expect.
但这不是我所期望的。
Q: how do I make this work?
问:我如何使这项工作?
回答by Qtax
If you want to match all the characters except \w
and -
you can use:
如果要匹配除\w
and之外的所有字符,-
可以使用:
[^\w-]
For example:
例如:
str.replaceAll("[^\w-]+", " ")
回答by Ian Roberts
Qtax's answeris probably the simplest in this particular case, since there is a built in complement to \W
, namely \w
. But in general, it's useful to know that Java's regex engine supports "intersections" in character classes with the &&
operator - you can say
在这种特殊情况下,Qtax 的答案可能是最简单的,因为 有一个内置的补充\W
,即\w
。但总的来说,知道 Java 的正则表达式引擎支持字符类与&&
运算符的“交集”很有用- 你可以说
[\W&&[^-]]
to match a single character that is both a \W
anda [^-]
, i.e. a non-word character but not also a hyphen.
匹配单个字符既是一个\W
和一个[^-]
,即非字字符,但不也连字符。
回答by alex
Use a negated character class...
使用否定字符类...
string = str.replaceAll("[^\w-]", " ")
\W
is great for convenience, but when you need to add extra characters to your pool, you need to use a character class with \w
.
\W
非常方便,但是当您需要向池中添加额外的字符时,您需要使用带有\w
.
The reason this doesn't work...
这不起作用的原因...
string = str.replaceAll("\W[^-]", " ")
...is because it's scanning for non-word characters ([^A-Za-z0-9_]
) followed by nota -
character. For example, /A
would be matched, but /-
would not be.
......是因为它的扫描非单词字符([^A-Za-z0-9_]
),其次是没有一个-
字符。例如,/A
会匹配,但/-
不会。