I am trying to find all characters, which are not letters(upper/lowercase), numbers, and underscore, and remove it.
stringA.replaceAll("[^a-zA-Z0-9_]","") // works perfectly fine
However, the following code could not even compile in Java:
stringA.replaceAll("\W","");
// or also
stringA.replaceAll("[\W]","");
// or also
stringA.replaceAll("[\\W]","");
If I use only "\\W"
rather than "\W"
, the above code turns out to be correct.
So, what is the differences between \W
, \\W
, and when to use brackets like [^a-zA-Z0-9_]