2

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"

alramdein
  • 810
  • 2
  • 12
  • 26
  • You have to type two backslashes inside a double-quoted Java `String` literal to include a single backslash character in the string. A backslash followed by anything else means something special. – Kevin Anderson Sep 20 '18 at 01:30
  • Oh, and the difference between `"\s+"` and `"\\s+"` is that `"\\s+"` gives you a string containing your desired regex of a backslash followed by an `s` followed by a plus sign, while `"\s+"` causes a compile error because `\s` isn't a valid Java string escape sequence. – Kevin Anderson Sep 20 '18 at 01:36

1 Answers1

2

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.

Vlam
  • 1,622
  • 1
  • 8
  • 17