1

I am splitting the string using ^ char. The String which I am reading, is coming from some external source. This string contains some \n characters.

The string may look like:

Hi hello^There\nhow are\nyou doing^9987678867abc^popup

when I am splitting like below, why the array length is coming as 2 instead of 4:

String[] st = msg[0].split("^");
st.length //giving "2" instead of "4"

It look like, split is ignoring after \n.

How can I fix it without replacing \n to some other character.

t.niese
  • 39,256
  • 9
  • 74
  • 101
ravi tiwari
  • 521
  • 1
  • 8
  • 24
  • 3
    If you read the Javadoc, you'll find that `split` works with regular expressions, and `^` has special meaning in a regex. Escape the character. `\\^` – Marko Topolnik Aug 26 '13 at 08:48

4 Answers4

1

the string parameter for split is interpreted as regular expression. So you have to escape the char and use:

st.split("\\^")

see this answer for more details

Community
  • 1
  • 1
mithrandir
  • 738
  • 1
  • 6
  • 17
0

If you want to split by ^ only, then

String[] st = msg[0].split("\\^");

If I read your question correctly, you want to split by ^ and \n characters, so this would suffice.

String[] st = msg[0].split("[\\^\\\\n]");

This considers that \n literally exists as 2 characters in a string.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

Escape the ^ character. Use msg[0].split("\\^") instead.

String.split considers its argument as regular expression. And as ^ has a special meaning when it comes to regular expressions, you need to escape it to use its literal representation.

0

"^" it's know as regular expression by the JDK.
To avoid this confusion you need to modify the code as below
old code = msg[0].split("^")
new code = msg[0].split("\\^")

Janny
  • 681
  • 1
  • 8
  • 33