Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string split giving unexpected result

Tags:

java

string

split

I have this string

String x = "2013-04-17T08:00:00.001,41.14806,-9.58972,-13.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-22.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-31.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-40.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-49.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-58.0,0.0,0.0,-20.0,4|2013-04-17T08:00:00.001,41.14806,-9.58972,-64.0,0.0,0.0,-20.0,4";

if i'm doing the split like this String vec2 [] = x.split(","); the output it will be this

2013-04-17T08:00:00.001
41.14806
-9.58972
-13.0
0.0
0.0
-20.0

and so on.

If I'm doing the split like this String vec2[] = x.split("|"); the output is this:

2
0
1
3
-
0
4
-
1
7
T
0
8
:
0
0
:

and so on.

And I would expect something similar to this:

    2013-04-17T08:00:00.001,41.14806,-9.58972,-13.0,0.0,0.0,-20.0,4
    2013-04-17T08:00:00.001,41.14806,-9.58972,-22.0,0.0,0.0,-20.0,4
    and so on

Any idea what's wrong?

like image 317
unpix Avatar asked May 08 '26 08:05

unpix


2 Answers

You need to escape the |:

String vec2[] = x.split("\\|");

That's because the argument to split() is a regex not a string.

In regexes, some characters have special meanings. The vertical bar | represens alternation. So if you want to split according to |, you need to write \\| which like telling: "Don't take | as a special character, take it as the symbol |".

like image 100
Maroun Avatar answered May 09 '26 21:05

Maroun


The argument to split is a regular expression and the "|" character has special meaning. Try escaping it \\|.

like image 37
forty-two Avatar answered May 09 '26 20:05

forty-two



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!