Reputation: 569
I want my program to accept search strings, for example: blue & berry (to find both of the words) bed | sleep | pillow(to find first one or the second one etc) When i recieve these string into my program, i use String.split() With "&" or "|" as separator.
String[] splited = input.split("|");
It works fine in the first case, but in the second case in separates each letter in the words, for example: b e d. Can i do something for it to be separated by words with this symbol, not just splited letter by letter?
Upvotes: 1
Views: 343
Reputation: 195
String.split(String)
uses regular expressions and | is a special character in regex. Use \|
to refer to a literal |
, and \\
to escape the \
for Java. Resulting in \\|
.
Upvotes: 3
Reputation: 11910
split()
is taking a regexp as argument. |
means or, so you are splitting on "empty string or empty string", so it's splitting after every letter. If you want to split on "|" symbol, you have to escape it:
String[] splited = input.split("\\|");
Upvotes: 5