tags:

views:

38

answers:

1

I'm having trouble using gsub correctly:

Given this code:

"replace me".gsub(/replace me/, "this \\0 is a test")

The result is:

 "this replace me is a test" 

But what I am expecting is:

"this \0 is a test"

How do I use gsub to get the result I want?

+3  A: 

Escape it with another backslash so that gsub will know you want "\\0".

"replace me".gsub(/replace me/, "this \\\\0 is a test")

(Edit) if by "\0" you meant the byte 0x00, do this:

"replace me".gsub(/replace me/, "this \0 is a test")
Adrian
@Adrian. Nah I didn't mean "\0" as the byte 0x00
Frank
Say I have the string `string = 'this \0 is a test'` and I want to use this string as the second argument to gsub. Would `string.gsub(/\\/,'\\\\')` work? How do I escape `string` so that the `\0` is not replaced with the match?
Frank
Use two slashes.
Adrian