aspose file tools
The moose likes Java in General and the fly likes String.split() question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 forum!

JavaRanch » Java Forums » Java » Java in General
Bookmark "String.split() question" Watch "String.split() question" New topic

String.split() question

Stephanie Smith

Joined: Jun 28, 2001
Posts: 22
I have a String that is delimited by commas

Value1, value2 , value3

However i want to be able to allow a value that has a comma. So it would have to be escaped.....perahps

value1, value2, value3, value4\,HasAComma

Is there a way to use String.split() to parse this such that the returned values


Thanks for any advice. wasn't sure if this could be accomplished via a regular expression or not.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 31551

Stephanie Smith wrote:Thanks for any advice. wasn't sure if this could be accomplished via a regular expression or not.

Yes. In the Pattern class JavaDoc look at positive/negative lookbehind. That lets you check the character before the character you are searching for.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Rob Spoor

Joined: Oct 27, 2005
Posts: 19897

But think about this: what if you want to end such a value with \? Do you then escape that too, e.g. value1, value2, value3, value4 ends with slash\\,value5? Because then it's going to be a bit harder; you have to check the number of preceding backslashes - even means don't escape the comma, odd means do.

But in the end you'll be redefining the CSV format. It has already thought of these issues. It uses value quoting to allow commas inside values, but also allows quotes inside values. Check out AccessingFileFormats under the Excel section to find a few libraries that can read and write to CSV files.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: String.split() question