James Fazio
James Fazio

Reputation: 6450

Java Splitting Strings

I have a string s that I want to split up so each part separated by the "|" symbol becomes an element of a string array.

Is this how I would go about doing so?

     String s = "FirstName1 LastName1|FirstName2 LastName2|FirstName3 LastName4|";
     String [] names = s.split("|");

I then want to add these elements to an ArrayList. I did the following

      for(int i = 0; i < names.length; i++)
        {
            friendsNames.add(names[i]);
        }

But my ArrayList reads as follows.

  Element 1: F
  Element 2: I
  Element 3: R
  Element 4: S
  Element 5: T
  Element 6: 
  Element 7: N

Any suggestions for where am I going wrong? etc.

Upvotes: 0

Views: 662

Answers (3)

erickson
erickson

Reputation: 269637

If you don't intend your delimiter to represent a regular expression, use the Pattern.quote() method to escape any special characters it contains.

String[] items = s.split(Pattern.quote("|"));

The pipe character, | indicates an alternative in a regular expression. So your split specification means, "split on any empty string, or any empty string." There are empty strings between every character, so that's why every character is split apart.

Special regex characters, like pipe, can be "escaped" with \. This disables it as a special character, and makes it match the | character in input instead.

To complicate things, \ has special meaning in Java character and character string literals, so it needs to be escaped too—with another \ character! This means that, altogether, your delimiter should be "\\|".

Upvotes: 0

RealHowTo
RealHowTo

Reputation: 35372

You need to escape the "|" since its a special character in the regex world.

String [] names = s.split("\\|");

Why 2 "\" ?

For the regex expression, you escape the "|" with "\|". But since "\" is the escape character for Java, you need to escape it to preserve the "\" for the regex expression.

Upvotes: 7

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

The pipe is special character in a regular expression accepted by the split method. Therefore you must escape that character so that it is interpreted as a separator char.

import static java.util.Arrays.asList;
//...
String s = "FirstName1 LastName1|FirstName2 LastName2|FirstName3 LastName4|";
List<String> items = asList(s.split("\\|"));

Upvotes: 1

Related Questions