简体   繁体   中英

Java: Split line by Unix new line character

I have this data in my input file u,9,1,bid\nu,11,5,ask\nq,best_bid\nu,10,2,bid\nq,best_bid\no,sell,1\nq,size,10\nu,9,0,bid\nu,11,0,ask\n How can I split it by \n so the formatted line will be

u,11,5,ask
q,best_bid
u,10,2,bid
q,best_bid
o,sell,1
q,size,10
u,9,0,bid
u,11,0,ask

I've already tried String[] s = line.split("\\n") but this didnt help me!

This is to explain why line.split("\\n") doesn't work. See below for a quicker solution.

"\\n" matches a newline . Your file contains literal \n s (that is, backslashes followed by the letter "n") instead, so you need to escape the backslash as well.

line.split("\\\\n")

Then you can join them with a \n .

So

String joined = String.join("\n", line.split("\\\\n"));
System.out.println(joined);

Which outputs

u,9,1,bid
u,11,5,ask
q,best_bid
u,10,2,bid
q,best_bid
o,sell,1
q,size,10
u,9,0,bid
u,11,0,ask

Having said that, if you don't intend to do any intermediate step with the result of splitting the line, you might as well replace the literal \n with an actual newline

line.replace("\\n", "\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM