0

I want to remove all break lines recursively from string with doubles quotes but I'm only removing one.

I'm doing this but I just remove one:

string.gsub(/\"(.*)\s(.*)\"/,'\1,\2')
fcastillo
  • 938
  • 1
  • 11
  • 24
  • Without any knowledge of Ruby, I'm guessing a `/g` flag would do it: `string.gsub(/\"(.*)\s(.*)\"/g,'\1,\2')` (Note that `\s` matches a whitespace character, not just a ‘break line[sic]’.) – Biffen Jan 30 '15 at 12:53
  • @fcastillo post an example along with expected output. – Avinash Raj Jan 30 '15 at 12:59
  • `\s` is not a breakline, it will match every space and tab. – BroiSatse Jan 30 '15 at 13:02
  • anyone mark this question as duplicate of http://stackoverflow.com/questions/632475/regex-to-pick-commas-outside-of-quotes , here is the regex https://regex101.com/r/fS8xR4/2 – Avinash Raj Jan 30 '15 at 13:32
  • Well, I want to read a CSV file in Rails and in some fields exists a break line and Rails detect that it's the end of file so I want to remove break lines that are between doubles quotes. – fcastillo Jan 30 '15 at 14:16
  • @Biffen: Ruby doesn't support the `/g` (global) modifier; that's what the `gsub()` method is for. That's as opposed to to `sub()`, which only does one substitution. – Alan Moore Jan 30 '15 at 19:36

1 Answers1

1

I would do:

string = 'hello "there cruel world"'

string.gsub(/\"[^"]+?\"/) do |match|
  match.gsub(/\s+/, ', ')
end

#=> 'hello "there, cruel, world"'

Surely it is possible with a single regex, however this way is much more readable.

BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • It doesn't work good because in string var still have the same value: `string.gsub(/\"[^"]+?\"/) do |match| eoo += match.gsub(/\s+/, ', ') end` In eoo = "there, cruel, world" but string = 'hello "there cruel world"' – fcastillo Jan 30 '15 at 14:42
  • Then change first `gsub`, to `gsub!` – BroiSatse Jan 30 '15 at 14:47