Java replaceAll("\\s+") vs replaceAll("\\\\s+") [duplicate]
Asked Answered
F

1

7

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

Filagree answered 27/11, 2014 at 14:11 Comment(2)
\ is written as \\ in Java. This should help you.Barroom
This should help to solve your problem: #4654331Fye
C
20

\\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
Capstone answered 27/11, 2014 at 14:14 Comment(4)
"...followed by s one or more times." Do u mean symbol "s" or spaces?Filagree
But where is the first "\" here "\sbasdef"?Filagree
@MaximGotovchits - the character s not spaces. The first `\` will be escaped.Capstone
It also removes control characters like new line, tab, etc. Example: " \r \n\n \t ".replaceAll("\\s+","" ).length() == 0 >> trueCotidal

© 2022 - 2024 — McMap. All rights reserved.