Split function does not work properly

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

String empName="employee name | employee Email"; String[] empDetails=empName.split("|"); 

he gives me the result as

 empDetails[0]="e"; empDetails[1]="m"; empDetails[2]="p"; empDetails[3]="l"; empDetails[4]="o"; empDetails[5]="y"; empDetails[6]="e"; empDetails[7]="e"; . . . 

but when i try to execute the code

 String empName="employee name - employee Email"; String[] empDetails=empName.split("-"); 

it gives me

  empDetails[0]="employee name "; empDetails[1]=" employee Email"; 

why the java split function cannot split the string separated by "|"

+4
source share
4 answers

The String # split () method accepts regex , not String .

Since | is a metacharacter, and it has a special meaning in regular expression.

It works when you avoid it.

 String[] empDetails=empName.split("\\|"); 

Update:

Special character handling in java: OFFICIAL DOCS .

As a note:

In java method names begin with small letters .it should be split() not split() ..not the capital and small s

+13
source

but my question is why should we use escape in the case of "|" not for "-"

Because "|" is a regular expression metacharacter. It means "alternating"; for example, "A|B" means matching "A" or "B" . If you have trouble understanding Java regular expressions, javadocs for Pattern describes the full Java regex syntax.

So when you break into "|" (without escaping!), you indicate that the delimiter is "nothing or nothing" and matches each character of the target string.

(For the notation, "-" also a metacharacter, but only in the character group "[..]" . In other contexts, escaping is not required.)

+5
source

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

+3
source

Try

 String[] empDetails=empName.split("\\|"); 
+1
source

Source: https://habr.com/ru/post/1502734/


All Articles