0

I would like to split a String by " | " in Java. I found split method of String class and it expects a regex expression for split delimeter but I don't know how to form a regex expression for " | ".

For example, a string is "AA | BB | CC" and I would like to get only AA, BB and CC as a string array.

kee
  • 10,969
  • 24
  • 107
  • 168

7 Answers7

3
String string = "AA|BB|CC";
String[] arr = string.split("\\|");
for (String s : arr) {
    System.out.println(s);
}

The above code prints:

AA
BB
CC
Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48
2

Use a regular expression for that, but the | char is a special char so you must scape it.

"AA | BB | CC".split("\\s*\\|\\s*");

Javier Diaz
  • 1,791
  • 1
  • 17
  • 25
1

It is string.split("\\|") (pipe must be escaped).

qqilihq
  • 10,794
  • 7
  • 48
  • 89
1

| is a special character in a regexp so you have to escape it.

Try: string.split("\\|")

jan.vdbergh
  • 2,129
  • 2
  • 20
  • 27
1

The regular expression passed to the split method should be: \\|.

String text = "AA | BB | CC";
text.split("\\|")); // [AA ,  BB ,  CC]

If you want to get rid of the spaces then:

text.split("\\s*\\|\\s*")); // [AA, BB, CC]
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
1

| is an keyword in RegEX.

String.split() takes RegEx as argument. You have to escape it. You can do this.

string.split(" \\| ");
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49
1

string.split("\\|") does the work.

  • split() splits the string according to regex
  • \ is needed to escape the regex' meaning of the pipe as "or"
  • second back slash is need to escape the first back slash for java compiler.
AlexR
  • 114,158
  • 16
  • 130
  • 208