Java replaceAll("\\s+") vs replaceAll("\\\\s+")

Maxim Gotovchits picture Maxim Gotovchits · Nov 27, 2014 · Viewed 35.5k times · Source

What's the difference between replaceAll("\\s+") and replaceAll("\\\\s+")? Usually I use \\s+ but sometimes I see \\\\s+.

Answer

TheLostMind picture TheLostMind · Nov 27, 2014

\\s+ --> replaces 1 or more spaces.

\\\\s+ --> replaces the literal \ followed by s one or more times.

Code:

public static void main(String[] args) {
    String s = "\\sbas  def";
    System.out.println(s);
    System.out.println(s.replaceAll("\\s+", ""));
    System.out.println(s.replaceAll("\\\\s+", ""));

}

O/P :

\sbas  def
\sbasdef
 bas  def