Kristian Vukusic
Kristian Vukusic

Reputation: 3324

Splitting Strings in java around the '|' character

I have this

String str = "a,pnp,a|pnp,lab2|pnp,a|pnp,lab2,utr,utr";
String[] strings = str.split("|");

This code won't split around the '|' character, instead it splits every character like

strings[0] == "a";
strings[1] == ",";

and so on.

How to get this working to get

strings[0] == "a,pnp,a"
strings[1] == "pnp,lab2"
...

Upvotes: 1

Views: 139

Answers (5)

trutheality
trutheality

Reputation: 23455

Just to the add to the options of escaping the | character:

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504032

You could escape the | symbol, as other answers have showed. Personally I'd suggest downloading Guava and using Splitter instead. While that may be seen as overkill for a single statement, in my experience it would be a rare project which couldn't be made more readable by various bits of Guava.

I'd personally use a list instead of an array if possible, so:

private static final Splitter PIPE_SPLITTER = Splitter.on('|');
...

// Or an immutable list if you don't plan on changing it afterwards
List<String> strings = Lists.newArrayList(PIPE_SPLITTER.split(str));

It's possible that I'm just overly-allergic to regular expressions, but I really don't like using an API which deals with regular expressions unless I'm really trying to use patterns which warrant them.

Upvotes: 1

Egalitarian
Egalitarian

Reputation: 2228

public String[] split(String regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

So, you should try String[] arrayOfStrings = str.split("\|");

Upvotes: 0

MByD
MByD

Reputation: 137442

split() takes a regular expression, and | is reserved for regex OR, so you need to escape it:

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

or even better:

String[] strings = str.split(Pattern.quote("|"));

Upvotes: 6

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85809

use

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

Upvotes: 1

Related Questions