Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String split with multicharacter delimiter

I'm fairly new to Java and I thought this worked the same as with other languages.

For a string:

String line = "3::Daniel::Louis||##2::Leon: the Professional::1994||6::Jean::Reno||7::Gary::Oldman||8::Natalie::Portman||##3::Scarface::1983||9::Al::Pacino||10::Michelle::Pfeiffer";

I want to split it at every ||##.

But:

for(String s : line.split("||##")) {
    System.out.println("|"+s+"|");
 }

returns:

||
|3|
|:|
|:|
|D|
|a|
|n|
|i|

... etc.

I was expecting:

3::Daniel::Louis

Leon: the Professional

... etc.

What am I doing wrong?

like image 282
David Homes Avatar asked Dec 04 '22 14:12

David Homes


1 Answers

You have to escape the | character since it's a regex metacharacter for logical OR

So I would use

line.split("\\|\\|##"))

Note that You have to escape the slash as well that is why I use

\\|

instead of

\|

To escape that metacharacter

like image 141
gtgaxiola Avatar answered Dec 11 '22 05:12

gtgaxiola