I am trying to split the string using Split function in java
String empName=\"employee name | employee Email\";
String[] empDetails=empName.
Try
String[] empDetails=empName.split("\\|");
but my question is why we have to use escape in case of "|" and not for "-"
Because "|"
is a regex meta-character. It means "alternation"; e.g. "A|B"
means match "A"
or "B"
. If you have problems understanding Java regexes, the javadocs for Pattern
describe the complete Java regex syntax.
So when you split on "|"
(without the escaping!), you are specifying that the separator is "nothing or nothing", and that matches between each character of the target string.
(For the record, "-"
is also a meta-character, but only in a "[..]"
character group. In other contexts it doesn't require escaping.)
String#split() method accepts a regex
and not a String
.
Since |
is a meta character, and it's have a special meaning in regex.
It works when you escape that.
String[] empDetails=empName.split("\\|");
Update:
Handling special characters in java:OFFICIAL DOCS.
As a side note:
In java method names starts with small letters.it should be split()
not Split()
..not the capital and small s
You should use .split("\\|");
instead of .split("|");