Question about String - gsub

Hi guys, I have a specific need with gsub from the String class.

I would like when I perform a gsub on a string, when it match with my regex, to replace the matches with the match prefixed by \.

This is the code I tried:

puts ".salad./".gsub(/([.\/])/, "\\\\1")

But I got that result:


I expect that result (to make you understand):


Is the goal here to essentially escape a string so it can be used in a regex?

Basically, I provide an easy way to use sed command for the user, without thinking about the complexity of that command.

So when the user is calling that function, when I get the user entry, I would like to perform a test on that entry to escape all special characters sed can badly interpret.

It’s for that function:

def replaceTextAllFilesRecursivelyNamed(path : String, filename : String, text : String, newText : String)
            regex = //
            replacement = ""

            requestedCommands = <<-CMD
                                find -name #{filename} -exec sed -i 's/#{text.gsub(regex,replacement)}/#{newText.gsub(regex,replacement)}/' {} \\;

            process = runSystemCommand(requestedCommands)

            if !process.success?

Do you get what I try to do ?

If that’s the use case, I’d just run the string thru Regex - Crystal 1.12.2 and not try and do it yourself.

1 Like

That is really magic :smiling_face_with_tear: Thanks a lot my friend

I guess you add one more \ in your replacement string. (if you prefer replace it yourself instead of use Regex.escape), you need double \ to output the raw \ in the string, and use %q to avoid explain the \ as escaped char.

puts ".salad./".gsub(/([\.\/])/, %q(\\\1))
# \.salad\.\/

BTW: Ruby use a more advanced regexp engine than Crystal, so, not all regexp expression work well on both langauge.

I will probably to move to your solution, because I noticed on my last experiment that Regex.escape don’t do exactly what I want I just make the generated system unusable. I need to fix that