What's the difference between replaceAll("\\s+")
and replaceAll("\\\\s+")
? Usually I use \\s+
but sometimes I see \\\\s+
.
Asked
Active
Viewed 4.8k times
6

Maxim Gotovchits
- 729
- 3
- 11
- 22
-
\ is written as \\ in Java. This should help you. – Maroun Nov 27 '14 at 14:13
-
This should help to solve your problem: http://stackoverflow.com/questions/4653831/regex-how-to-escape-backslashes-and-special-characters – peterremec Nov 27 '14 at 14:13
1 Answers
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
-
"...followed by s one or more times." Do u mean symbol "s" or spaces? – Maxim Gotovchits Nov 27 '14 at 14:15
-
-
@MaximGotovchits - the character `s` not spaces. The first `\\` will be escaped. – TheLostMind Nov 27 '14 at 14:18
-
It also removes control characters like new line, tab, etc. Example: " \r \n\n \t ".replaceAll("\\s+","" ).length() == 0 >> true – Gabe Apr 24 '16 at 19:25