1

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?

2 Answers 2

5

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("\\|");
Sign up to request clarification or add additional context in comments.

Comments

3

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 \\|.

Comments

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.