I am trying to split the string using Split function in java
String empName=\"employee name | employee Email\";
String[] empDetails=empName.
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.)