Tirafesi
Tirafesi

Reputation: 1479

String.split() not working as intended

I'm trying to split a string, however, I'm not getting the expected output.

String one = "hello 0xA0xAgoodbye";
String two[] = one.split(" |0xA");
System.out.println(Arrays.toString(two));

Expected output: [hello, goodbye]

What I got: [hello, , , goodbye]

Why is this happening and how can I fix it?

Thanks in advance! ^-^

Upvotes: 1

Views: 377

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627545

This result is caused by multiple consecutive matches in the string. You may wrap the pattern with a grouping construct and apply a + quantifier to it to match multiple matches:

String one = "hello 0xA0xAgoodbye";
String two[] = one.split("(?:\\s|0xA)+");
System.out.println(Arrays.toString(two));

A (?:\s|0xA)+ regex matches 1 or more whitespace symbols or 0XA literal character sequences.

See the Java online demo.

However, you will still get an empty value as the first item in the resulting array if the 0xA or whitespaces appear at the start of the string. Then, you will have to remove them first:

String two[] = one.replaceFirst("^(?:\\s|0xA)+", "").split("(?:\\s+|0xA)+");

See another Java demo.

Upvotes: 1

Shafin Mahmud
Shafin Mahmud

Reputation: 4081

(\\s|0xA)+ This will match one or more number of space or 0xA in the text and split them

Upvotes: 2

NPE
NPE

Reputation: 500933

If you'd like to treat consecutive delimiters as one, you could modify your regex as follows:

"( |0xA)+"

This means "a space or the string "0xA", repeated one or more times".

Upvotes: 4

Related Questions