0

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?

3
  • Please provide all relevant code, it will be easier to help. Commented Nov 7, 2013 at 13:10
  • Are you actually getting =0.2<newline>Test =100<newline>[ for the strArr[1]? Commented Nov 7, 2013 at 13:13
  • nope, just =0.2 (print vs println) Commented Nov 7, 2013 at 13:16

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, it breaks the string on M in GTM, but why does it break on newline?
@ipavlic What do you mean?
Yep, that's it. Didn't know .split() required regex. Thank You.
The original poster claims that strArr[1] is =0.2. Why it would break the string on newline as well as on any of D, L, M?
1

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.

Comments

1

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.