How to Split a String with Escaped Delimiters

5 years ago by in How To, Utilities Tagged: , ,

Let say we need to split the following String into an array of four elements.

Messages,Hello\,World,Hobbies,Java\,Programming

We want to ignore the escaped comas and produce the following array.

Messages
Hello,World
Hobbies
Java,Programming

Using the String.split(",") will produces an array of six elements, which is not what we want. Regular expressions provide the look around assertion which allows us to ignore the comas which are preceded by the escape character \.

String s = "Messages,Hello\,World,Hobbies,Java\,Programming";
System.out.println(Arrays.toString(s.split("(?<!\\\\),")));
Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

Leave a Comment


Time limit is exhausted. Please reload the CAPTCHA.