-1

Why is the pipe symbol escaped two time in the below code. Is "\|" is also a regex? If so, what does it mean?

String str[], str1 = "This|is|a|sentence"
str = str1.split("\\|");
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alvin3001
  • 109
  • 1
  • 9

2 Answers2

3

Why is pipe symbol escaped two times in the below mentioned section of code?

It isn't, but it's understandable you'd think it was.

The regex pattern is \|, because | means alternation unless you escape it.

Because we're writing that pattern in a string literal, and \ is special in string literals, we have to escape it — with a \. So we get "\\|".

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Well, uhm, to be exact you could say that "in string literals, the backslash itself has to be escaped, with... A backslash. Hence the output". – fge Nov 09 '15 at 13:54
0

\\| means a literal pipe symbol, |.

If it were not escaped, it is the alternation operator, so you'd be splitting on empty string or empty string, so you'd get an array of the individual characters.

If you want to put a \ in a Java string literal, you have to escape it with itself, since \ is used to mark control characters like \n (unix new line).

Were you to write "\|", your code would not even compile, since | is not a control character. You can see all of the control characters here: What are all the escape characters in Java?

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243