On Dec 19, 2008, at 2:58 PM, Frederick Cheung wrote:
> On 19 Dec 2008, at 19:48, Corey Murphy <rails-mailing-l...@andreas-
> s.net> wrote:
>
>> Why would the following regular expression produce the results below?
>>
>> ****input:
>> john,doe,"1,200.99",training,12345
>>
>> ****code executed on input:
>> values = line.split(/("\d*,\d+\.\d*")|,/)
>>
>> ****output:
>> ["john","doe","","1,200.99","","training","12345"]
>>
> Pretend you're split. You see the comma after doe so you split. Then
> you see the other part of your regex and so you split again, resulting
> in the empty array
>
> Fred
>> What's up with the two empty array indexes that are generated during
>> the
>> split surrounding my dollar value?
>>
>> The regular expression is pretty explicit and the input string
>> doesn't
>> contain anything that should cause them when run through the
>> expression,
>> yet there they are so obviously I'm doing something wrong in my
>> regexp.
>> Help.
I think you actually get:
=> ["john", "doe", "", "\"1,200.99\"", "", "training", "12345"]
as your output. (At least I do.)
However, it looks like your input is CSV so why not let a CSV library
do the heavy-lifting for you:
irb> require 'rubygems'
=> true
irb> require 'fastercsv'
=> true
irb> FasterCSV.parse_line(line)
=> ["john", "doe", "1,200.99", "training", "12345"]
Note: FasterCSV becomes the CSV in the standard library for Ruby 1.9,
but it's a gem before that so look at the rdocs/ri for whatever you're
using.
-Rob
Rob Biedenharn http://agileconsultingllc.com
[email protected]
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---