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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String.split() question" Watch "String.split() question" New topic
Author

String.split() question

Stephanie Smith
Greenhorn

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
are

value1
value2
value3
value4,HasAComma

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

Joined: May 26, 2003
Posts: 29233
    
138

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.


[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
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String.split() question
 
Similar Threads
what to do about chained if-then-else?
problem with struts2 drop down
Record store gets overwritten
how to process the "java -verbose:class" output info in the command.
How to Handle Properties