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 ( "|"...




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

  1. Thanks for that, it was a lifesaver

    ReplyDelete
  2. Thank you for posting very useful tips! I found your website perfect for my needs.I always like your article because you have provide every time informative post..Essay Editor Service

    ReplyDelete
  3. wow, awesome blog.Thanks Again. Much obliged 먹튀검증 I believe you are the person I was looking for 먹튀검증

    ReplyDelete
  4. Are you looking for custom packaging for your CBD boxes? Well, look no further Because Custom CBD Boxes is here for you. There are two major reasons as to why you should use a customized box for your CBD boxes; market size and CBD unique position in society.

    ReplyDelete
  5. Your site is very good and informational for me. We are the best suppliers of Custom Printed CBD Boxes in the UK. If anyone has interest in them please visit our website for more products.

    ReplyDelete

emo-but-icon

SUBSCRIBE


item