Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 852
Maxim Gotovchits Avatar asked Nov 27 '14 14:11

Maxim Gotovchits


People also ask

What is replaceAll \\ s?

The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.

What is the difference between Replace () and replaceAll ()?

The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)

Does Java string replace replace all?

String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex. There are two overloaded methods available in Java for replace() : String. replace() with Character, and String.

How do you replace multiple spaces in Java?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.


1 Answers

\\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
like image 121
TheLostMind Avatar answered Sep 27 '22 23:09

TheLostMind