Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

| not recognized in java string.split() method [duplicate]

Tags:

java

string

I am having problems with the java string.split method.

I have a string word like so, which equals- freshness|originality. I then split this string like so:

   String words[] = word.split("|");

If I then output words[1], like so:

    t1.setText(words[1]); 

It gives me the value f. I have worked out that this is the f in the word freshness.

How can I split the string properly so that words[1] is actually originality? Thanks for the help!

like image 333
James Avatar asked Dec 09 '22 09:12

James


2 Answers

You should escape it:

String words[] = word.split("\\|");

Check this explanation in similar question here: Why does String.split need pipe delimiter to be escaped?

String object's split() method has a regular expression as a parameter. That means an unescaped | is not interpreted as a character but as OR and means "empty string OR empty string".

like image 112
Micer Avatar answered Dec 10 '22 23:12

Micer


You need to escape the pipe because java recognizes it as a Regular Expression OR Operator.

line.split("\\|")

"|" gets is parsed as "empty string or empty string," which isn't what you are trying to find.

For the record

... ? . + ^ : - $ *

are all Regex Operators and need to be escaped.

like image 35
jeremyjjbrown Avatar answered Dec 10 '22 21:12

jeremyjjbrown