3

When I split the string "1|2|3|4" using the String.split("|") I get 8 elements in the array instead of 4. If I use "\\|" the result is proper. I am guessing this has something todo with regular expressions. Can anybody explain this?

3
  • Just pointing out--the amount of time this confusion took probably cost you more than you will save by using regular expressions (over just coding the damn thing) over your entire career unless you do a lot of shell scripting. Commented Sep 24, 2010 at 20:15
  • 1
    I never intended to use regular expressions..the damn API is using automatically.. what am I supposed to do then? Commented Sep 24, 2010 at 20:19
  • 1
    Unfortunately the String.split() method always uses regexes. There are more flexible APIs available, though. Commented Sep 24, 2010 at 20:34

3 Answers 3

7

You're right. | is a special character for alternation. The regular expression | means "an empty string or an empty string". So it will split around all empty strings, resulting 1 element for each character in the string. Escaping it \| make it a normal character.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply.. is & is also a special character?
@why: No it's not. See download-llnw.oracle.com/javase/6/docs/api/java/util/regex/…. You could use \Q...\E to make sure the ... won't be interpreted as special characters.
@why should I tell you my name: regular-expressions.info/reference.html
3

If you want to split a string without using a regex, I'd recommend the Splitter class from Guava. It can split on fixed strings, regexes and more.

Iterable<String> split = Splitter.on('|').split("1|2|3|4");

Comments

1

| is OR in Java regular expression syntax, basically splitting 1|2|3|4 with | is equal to telling String#split() to "split this string between empty OR empty) which means it splits after every character you have in the original string.

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.