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("\\|");
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("\\|");
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 "\\|"
.
\\|
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?