Andy McCall
Andy McCall

Reputation: 464

Split Strings by "|"

I'm have some data in a txt file like in this form

| item_id | channel | rank | head | body | source | timestamp | link_1_id | link_1_manual/auto | link_1_name/title | link_2_id | link_2_manual/auto | link_2_name/title | ... |

An i need to split it at the pipeline characters. However if I do:

String[] cols = line.split("|");

It will split the data by every character which is not what I want. What do I need to do to split by "|"?

Upvotes: 1

Views: 172

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. "|" has special meaning in Regular Expression.

2. So use "\" before the "|" to remove its special meaning.

Example:

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

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198163

Use

line.split("\\|");

The split pattern is interpreted as a regular expression, and | has a special meaning in regular expressions -- it's not interpreted as just the character alone.

Upvotes: 10

Related Questions