-2

My input string is :

"& is here "& is here also, & has again occured""

Using gsub method in Ruby language, is there a way to substitute character '&' which is occuring within double quotes with character '$', if gsub method doesnt solve this problem, is there any other approach which can be used to address this problem.

Since first arguement in gsub method can be a regex, so matched regex will be substituted by the second arguement, getting a right regex for identifying might also solve this problem since it can be substituted in the gsub method for replacing '&' with '$'.

Expected output is as shown :

& is here "$ is here also , $ has again occured"
Manu
  • 40
  • 1
  • 7
  • Please use English punctuation when you write in English. – sawa Jan 13 '16 at 07:40
  • 1
    I'd match the quoted substrings and replace the ampersands inside each match. – Wiktor Stribiżew Jan 13 '16 at 07:47
  • It can't be done in any robust way with regex. – pguardiario Jan 13 '16 at 07:59
  • @pguardiario: It can't be done at all with regex, given that regex is only search (it does not cover replacing). But it can be done with regex and other stuff :) – Amadan Jan 13 '16 at 08:09
  • Sorry @sawa will you highlight the mistakes on my current post so I can improve on this. – Manu Jan 13 '16 at 08:43
  • @sawa I have made changes to the highlighted portions , but i dont know if its right or not , this time instead of highlighting make the corrections , so that I will get a better understanding . Thanks – Manu Jan 13 '16 at 11:38
  • @Manu In English, you shouldn't put a space before colons commas, etc., and you should end a sentence with a period or an exclamation or question mark (unless it ends with things like a block of formatted code). – sawa Jan 13 '16 at 11:52

1 Answers1

1
str = %q{& is here "& is here also , & has again occured"}
str.gsub!(/".*?"/) do |substr|
  substr.gsub(/&/, '$')
end
puts str
# => & is here "$ is here also , $ has again occured"

EDIT: Just noticed that stribizhev proposed this way before I wrote it.

Amadan
  • 191,408
  • 23
  • 240
  • 301