From: Jim Menard Date: 2000-11-02T22:40:01+09:00 Subject: [ruby-talk:5988] Putting backslash before \1 I am trying to create a string by preceeding all backslashes or tabs in the original with a backslash. For example, makeSafe("a\tb") => "a\\\tb" makeSafe("a\\b") => "a\\\\b" I can't figure out how to use gsub() to do this. Specifically, I can't figure out how to preceed '\1' with a backslash. For example (output below): str = "tab:\tand backslash:\\done" puts str.gsub(/([\\\t])/, '\1') # Should do nothing. puts str.gsub(/([\\\t])/, '\\1') # Should do nothing ('\\1' same as '\1'). puts str.gsub(/([\\\t])/, '\\\1') # Help! Want backslashes before \1. puts str.gsub(/([\\\t])/, '\\' + '\1') # How about this? No good. Output: tab: and backslash:\done ("tab:\tand backslash:\\done") tab: and backslash:\done ("tab:\tand backslash:\\done") tab:\1and backslash:\1done ("tab:\tand backslash:\\done") tab:\1and backslash:\1done ("tab:\\1and backslash:\\1done") (My workaround? Two separate substitutions that "know" what character they are looking for:) def makeSqlSafe(str) copy = str copy.gsub!(/\t/, "\\\t") copy.gsub!(/\\/, "\\\\") return copy end Any suggestions or better workarounds? Is this a Ruby bug, or am I misunderstanding the use of '\1' and '\\1'? Thanks for your time and help. Jim -- Jim Menard jimm@io.com http://www.io.com/~jimm/ BeOS developer #1283 "The reason why there is no good commercial Java develoment environment is that the only folks that are good enough to write one all use EMACS." -- Unknown, on comp.lang.java.programmer