0

Just a quick question:

String input = "sam|y|rutgers";
String[] splitInput = input.split("|");
System.out.println(Arrays.toString(splitInput));

Output:
[, s, a, m, |, y, |, r, u, t, g, e, r, s]

I would like to split at the pipe characters to get [sam,y,rutgers]

Any idea what I'm doing wrong here?

4 Answers4

8

Try with one of these

  • split("\\|")
  • split("[|]")
  • split(Pattern.quote("|"))
  • split("\\Q|\\E")

split method uses regex as parameter and in regex | means OR so your current expression means empty string or empty String.

If you want to make | simple literal you need to escape it. To do this you can

  • place \ before it in regex engine which in String will be written as "\\|".
  • use character class [...] to escape most of regex metacharacters like split("[|]")
  • or surround your special characters with \\Q and \\E which will make every character (regardless if it is special or not) simple literal. This solution is used in Pattern.quote("regex").
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

You may try this:

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

"|" is a special character(OR) so you need to escape that using a slash \\. As answered here An unescaped | is parsed as a regex meaning "empty string or empty string,"

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You can do it by StringTokenizer

StringTokenizer st2 = new StringTokenizer(input , "|");

    while (st2.hasMoreElements()) {
        System.out.println(st2.nextElement());
    }

default delimeter is " " space.

StringTokenizer st2 = new StringTokenizer(input );//it will split you String by `" "` space
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
1

\Q & \E are regex quotes.

String[] splitInput = input.split("\\Q|\\E");
4J41
  • 5,005
  • 1
  • 29
  • 41