6

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

Maxim Gotovchits
  • 729
  • 3
  • 11
  • 22

1 Answers1

19

\\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
khelwood
  • 55,782
  • 14
  • 81
  • 108
TheLostMind
  • 35,966
  • 12
  • 68
  • 104