Java Split String with Pipe (|) Parameter

Problem: Try to split String which is having delimiter as pipe(|)

public class TestSplit
{
  public static void main( String[] args )
  {
     String DELIMETER = "@";
    // String DELIMETER = "|";
    

    String line = "field1" + DELIMETER + "field2";

    String[] tempList = line.split( DELIMETER );
    int sizeOfArray = tempList.length;

    System.out.println( "sizeOfArray==>" + sizeOfArray );

    for( int i = 0; i < tempList.length; i++ ) {
      System.out.println( i + "==>" + tempList[i] );
    }
  }
}

Why Pipe(|) wont work as delimeter?

Java Syntax
String[] split(String regex)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
Logical operators
X|Y Either X or Y

-o-

Advertisements

One thought on “Java Split String with Pipe (|) Parameter

  1. By default, the pipe alone will act as a special character that will split the String into its individual characters (plus a space as the first element). In order to use the pipe delimeter as a literal character, pass in “\|” as regex. The pipe will then be read as an escape character and thus be treated as a literal character.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s