astralmaster
astralmaster

Reputation: 2465

Split string containing newline characters Java

Say I have a following string str:

GTM =0.2
Test =100
[DLM]
ABCDEF =5

(yes, it contains newline characters) That I am trying to split with [DLM] delimiter substring like this:

String[] strArr = str.split("[DLM]");

Why is it that when I do:

System.out.print(strArr[0]);

I get this output: GT

and when I do

System.out.print(strArr[1]);

I get =0.2

Does this make any sense at all?

Upvotes: 0

Views: 1108

Answers (4)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

use

 String[] strArr = str.split("\\[DLM]\\");

Instead of

 String[] strArr = str.split("[DLM]");

Other wise it will split with either D, or L, or M.

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208944

Escape the brackets

("\\[DLM\\]")

When you use brackets inside the " ", it reads it as, each character inside of the brackets is a delimiter. So in your case, M was a delimiter

Upvotes: 1

iajrz
iajrz

Reputation: 789

Yes, you're giving a regex which says "split with either D, or L, or M".

You should escape those boys like this: str.split("\[DLM\]");

It's being split at the first M.

Upvotes: 1

Maroun
Maroun

Reputation: 95948

str.split("[DLM]"); should be str.split("\\[DLM\\]");

Why?

[ and ] are special characters and String#split accepts regex.

A solution that I like more is using Pattern#quote:

str.split(Pattern.quote("[DLM]"));

quote returns a String representation of the given regex.

Upvotes: 5

Related Questions