I have a string
str = "'${1:textbox}',[${2:x},${3:y},${4:w},${5:h}]"
and I would like to replace all , between [ and ] with a single space.
I have attempted to use something like
str.gsub!(/(?<=\[)\,*?(?=\])/," ")
without success. However, if I replace \, in my expression with ., I get the expected output:
str.gsub!(/(?<=\[).*?(?=\])/," ")
== "'${1:textbox}',[ ]"
Could someone please explain the proper regex technique to use in this situation, and perhaps also explain why the examples I have posted above have failed and succeeded?
I am using ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]
It may be possible to do this with a single regex, but even if it is, I can guarantee it’ll be ugly beyond description. It’s a lot simpler to use “nested” substitution – use one gsub to find bracketed substrings, and then use another to swap out the commas:
I’m afraid I can’t explain why your attempts have failed – neither of them would run for me (ruby 1.8.7 / irb 0.9.5). IRB gave errors that vaguely said “Bad regexp syntax.” And I can’t quite grok how they’re supposed to work (edit: mu is too short has an awesome breakdown in his answer – check that out). Hope this is helpful anyway!