我试图找到所有不是字母(大写/小写)、数字和下划线的字符,并将其删除。
stringA.replaceAll("[^a-zA-Z0-9_]","") // works perfectly fine
但是,下面的代码甚至无法在 Java 中编译:
stringA.replaceAll("\W","");
// or also
stringA.replaceAll("[\W]","");
// or also
stringA.replaceAll("[\\W]","");
如果我只使用"\\W"
而不是"\W"
,上面的代码证明是正确的。
那么,\W
、\\W
之间有什么区别,以及何时使用 [^a-zA-Z0-9_]
最佳答案
However, the following code could not even compile in Java
Java 不知道该字符串将进入正则表达式引擎。双引号中的任何内容对于 Java 编译器来说都是字符串文字,因此它会尝试将 \W
解释为 Java escape sequence。 ,这是不存在的。这会触发编译时错误。
If I use only
\\W
rather than\W
, the above code turns out to be correct.
这是因为 \\
是一个有效的转义序列,意思是“单斜线”。当您在字符串文字中放置两个斜杠时,Java 编译器会删除一个斜杠,因此正则表达式引擎看到的是 \W
,而不是 \\W
So, what is the differences between
\W
,\\W
, and when to use brackets like[^a-zA-Z0-9_]
第三个是第二个的加长版;第一个不编译。
关于java - 正则表达式中\W,\\W,[^a-zA-Z0-9_]的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397243/