Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String.split() question

 
Stephanie Smith
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author & internet detective
Marshal
Posts: 34672
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic