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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:17:10  来源:igfitidea点击:

Replace all special character except one

javaregex

提问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 \wand -you can use:

如果要匹配除\wand之外的所有字符,-可以使用:

[^\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 \Wanda [^-], i.e. a non-word character but not also a hyphen.

匹配单个字符既是一个\W一个[^-],即非字字符,但不也连字符。

回答by alex

Use a negated character class...

使用否定字符类...

string = str.replaceAll("[^\w-]", " ")

\Wis 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, /Awould be matched, but /-would not be.

......是因为它的扫描非单词字符([^A-Za-z0-9_]),其次是没有一个-字符。例如,/A会匹配,但/-不会。