What is the difference between \\s+ and \s+

11.9k views Asked by At

I know one of the regular expression is "\s+" which is mean one or more whitespaces. But in many referenece that I saw,

Why they use double backslash "\\s+" instead of just one backslash "\s+" ?

For exemple in this code that I get in stackoverflow :

import java.math.*;
import java.util.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
public class Initials {
  public String getInitials(String s) {

    String r = "";
    for(String t:s.split("\\s+")){
      r += t.charAt(0);
    }
    return r;
  }


  void p(Object... o) {
          System.out.println(deepToString(o));
      }


}

And the output from this code is :

Example Input: "john fitzgerald kennedy"

Returns: "jfk"

1

There are 1 answers

0
Vlam On BEST ANSWER

In Java and some other programming languages, a backslash can be interpreted as part of the string itself and not part of the regular expression. So \\s in the string just means \s when it goes to the regular expression part. This means \\ just escapes the backslash itself so that it's a literal backslash.