What's the difference between replaceAll("\\s+")
and replaceAll("\\\\s+")
? Usually I use \\s+
but sometimes I see \\\\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.
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)
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.
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.
\\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With