Split function not working properly

后端 未结 4 2081
無奈伤痛
無奈伤痛 2021-01-19 04:07

I am trying to split the string using Split function in java

String empName=\"employee name | employee Email\";
String[] empDetails=empName.         


        
4条回答
  •  难免孤独
    2021-01-19 04:48

    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.)

提交回复
热议问题