Java String Split with Pipe Character Not Working - Solution




If you are working on Java, you might have run into this issue when you try to split a string based on a pipe character ("|"). It simply won't work. Split method in Java takes regex as an argument. There are certain characters including the pipe character which has special meaning in regex and are called meta characters. Here is a list of Java Regex meta characters

( ) [ ] { { \ ^ $ | ? * + . < > - = !


There are three ways to resolve this issue,

1. Use Pattern.quote()

Pattern is a class for handling regex expressions in Java. Pattern.quote() returns a literal pattern String for the specified String. Metacharacters or escape sequences in the input sequence will be given no special meaning.

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

2. Use Escape Characters

This is simple. Just escape the pipe character with double slash.

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

3. Use StringTokenizer to Split

You can use StringTokenizer to split strings and avoid all regular expression issues.

public static String[] splitUsingTokenizer(String original, String delimiters) 
{
     StringTokenizer token = new StringTokenizer(original, delimiters);
     ArrayList<String> list = new ArrayList<String>(original.length());
     while(token.hasMoreTokens())
     {
       list.add(token.nextToken());
     }
     return list.toArray(new String[0]);
}



Keep yourself subscribed for getting programmingfree articles delivered directly to your inbox once in a month. Thanks for reading!

Subscribe to GET LATEST ARTICLES!


Related

Java 734647647001795499

Post a Comment

emo-but-icon

SUBSCRIBE


item