2

I have this code:

String message = receiveMessage();
String[] reciv = message.split("|");

System.out.println("mess: " + message);
System.out.println("reciv: " + reciv[0]);

And this output:

mess: E|NAME
reciv: 

I look some strange, E|NAME is E|NAME*space**space**space**space**space**space**space*...

I try to copy the "spaces" and I can't. I'm thinking the "spaces" no are "spaces".

Sorry for my bad English, I'm Spanish.

2 Answers 2

7

split uses regex and in regex | has special meaning which is OR so "|" means empty string "" OR empty string "". Splitting on empty string means that

"ABC"

will split in these places (I will mark them with |)

"|A|B|C|"

producing array ["", "A", "B", "C", ""] but as split documentation says

Trailing empty strings are therefore not included in the resulting array

so last empty space is removed. So you get in result ["", "A", "B", "C"]


Now if you want make it | literal you need to escape it using for example

  • split("\\|")
  • or split("[|]").
  • or split(Pattern.quote("|"))
  • or split("\\Q|\\E")
Sign up to request clarification or add additional context in comments.

2 Comments

@Pshemo, Thanks..I didn't know about [] in Java's regexp...where could I read about that?
@Dedyshka [..] is character class. Lets say that you want to find characters between a and e. You could write regex that will match them as "a|b|c|d|e" or just use character class like [abcde] or use range operator - inside like [a-e]. Note that one character class can have few characters or charactes ranges inside and they order doesnt matter so all its elements are by default separated with OR operator so there is no need for explicitly usage | inside it. That is why it is treated as literal instead of regex metacharacter.
2

You can do like this

String message = receiveMessage();
message  = message.replaceAll("[\n\r\\s]", "");
String[] str1 = message.split("[|]");
for (int i = 0; i < str1.length; i++) {
    System.out.println(str1[i]);
}

3 Comments

why don't you use just trim?
@Dedyshka trim will remove the spaces front and end of the string.
@Prabhakaran I guess that there isn't any special conditions, so trim is also acceptable..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.