1

I'm wondering why I cannot split a text that contain the | as a separator in String. The splitting works fine when I use commas or the like..

Here is an SSCE

package tests;

public class Tests {        
    public static void main(String[] args) {

        String text1="one|two|three|four|five";
        String text2="one,two,three,four,five";

        String [] splittedText1 = text1.split("|");
        String [] splittedText2 = text2.split(",");

        for(String elem : splittedText1) System.out.println("text1="+elem);
        for(String elem : splittedText2) System.out.println("text2="+elem);
    }    
}

Any ideas why it doesn't work with "|" ??

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Ramses
  • 652
  • 2
  • 8
  • 30

2 Answers2

5

Since split(String regex) takes a regex and | is a meta character, you need to escape it.

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

Or you can simply use Pattern class

A compiled representation of a regular expression.

String[] splittedText1 = splittedText1.split(Pattern.quote("|"));
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
4

Because the split pattern is actually a regex. You need to escape |, since it has a special meaning in the context of a regular expression (it marks an alternative):

String [] splittedText1 = text1.split("\\|");
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80