Split function not working properly

后端 未结 4 2051
無奈伤痛
無奈伤痛 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:45

    Try

    String[] empDetails=empName.split("\\|");
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-19 04:52

    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

    0 讨论(0)
  • 2021-01-19 04:52

    You should use .split("\\|"); instead of .split("|");

    0 讨论(0)
提交回复
热议问题