Robert Klemme
3/20/2008 12:13:00 PM
2008/3/20, ciapecki <ciapecki@gmail.com>:
> On 19 Mrz., 22:28, Robert Klemme <shortcut...@googlemail.com> wrote:
> > On 19.03.2008 11:21, ciapecki wrote:
> >
> >
> >
> > > On 19 Mrz., 10:09, Xavier Noria <f...@hashref.com> wrote:
> >
> > >> My interpretation of what you need is:
> >
> > >> input = '111|"aaaa" bbbbb|c'
> >
> > >> fields = input.split('|')
> > >> fields[1].gsub!('"', '""')
> > >> fields[1] = %Q{"#{fields[1]}"}
> >
> > >> output = fields.join('|')
> >
> > >> Depending on the input that may not be valid, for example if fields[1]
> > >> may contain a pipe. Anyway being a mal-formed input assumptions depend
> > >> on the actual data.
> >
> > > your solution works, and thanks for that,
> > > I am waiting though for a regexp solution,
> >
> > Even 2 regexps:
> >
> > irb(main):001:0> input = '111|"aaaa" bbbbb|c'
> > => "111|\"aaaa\" bbbbb|c"
> > irb(main):002:0> input.gsub(/[^|]+/) {|m| m.gsub!(/"/,'""') ?
> > '"'<<m<<'"' : m}
> > => "111|\"\"\"aaaa\"\" bbbbb\"|c"
> > irb(main):003:0> puts input.gsub(/[^|]+/) {|m| m.gsub!(/"/,'""') ?
> > '"'<<m<<'"' : m}
> > 111|"""aaaa"" bbbbb"|c
> > => nil
> >
> > Cheers
> >
> > robert
>
>
> this is just great,
> thanks robert for this
You're welcome. Btw, this is even better (also faster)
irb(main):003:0> input = '111|"aaaa" bbbbb|c'
=> "111|\"aaaa\" bbbbb|c"
irb(main):004:0> input.gsub(/"/,'""').gsub(/[^|]*"[^|]*/,'"\\&"')
=> "111|\"\"\"aaaa\"\" bbbbb\"|c"
irb(main):005:0> puts input.gsub(/"/,'""').gsub(/[^|]*"[^|]*/,'"\\&"')
111|"""aaaa"" bbbbb"|c
=> nil
This could even be a bit faster:
irb(main):006:0> input.gsub(/"/,'""').gsub(/[^|"]*"[^|]*/,'"\\&"')
=> "111|\"\"\"aaaa\"\" bbbbb\"|c"
Kind regards
robert
--
use.inject do |as, often| as.you_can - without end