LordBullington
LordBullington

Reputation: 219

Java .split("|") not working

I just ran into the problem that the split method for strings wouldn't work with character "|" as an argument. It somehow separates each character in the string.

Code:

String[] res = "12345|6".split("|");
Log.d("split", Arrays.toString(res));

Output:

split﹕ [, 1, 2, 3, 4, 5, |, 6]

Upvotes: 16

Views: 16688

Answers (6)

Sneha Mule
Sneha Mule

Reputation: 715

public static void main(String[] args) {
    String data = "12345|6|7|990";
    String[] arr = data.split("\\|");
    for(int i = 0 ; i< arr.length; i++){
      System.out.println(arr[i]);
    }
  }

O/p : 12345
6
7
990

Upvotes: -1

Sangram kumar sahoo
Sangram kumar sahoo

Reputation: 1

You can try this, simple and easy.

String[] res = "12345|6".split("[|]");

Upvotes: 0

Vasu
Vasu

Reputation: 22422

Use escape character before | like below:

String[] res = "12345|6".split("\\|");

Similar "escape character logic" is required, when you are dealing/splitting with any of the below special characters (used by Regular Expression):

  • OR sign (|)
  • question mark (?)
  • asterisk (*)
  • plus sign (+)
  • backslash (\)
  • period (.)
  • caret (^)
  • square brackets ([ and ])
  • dollar sign ($)
  • ampersand (&)

Upvotes: 30

user7176550
user7176550

Reputation: 1541

If you have split using "||" then you use :

      yourstring.split(Pattern.quote("||"))

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172428

You can try to escape it like this:

String[] res = "12345|6".split("\\|");

Pipe has special meaning in regular expression and it allows regular expression components to be logically ORed. So all you need to escape it using the \\

Upvotes: 6

Erveron
Erveron

Reputation: 1928

| is a regular expression key character and split() works with regualar expressions. Escape it like this: \\|

Upvotes: 6

Related Questions