Backslashes in gsub (escaping and backreferencing)
Posted
by polygenelubricants
on Stack Overflow
See other posts from Stack Overflow
or by polygenelubricants
Published on 2010-06-12T11:48:07Z
Indexed on
2010/06/12
11:52 UTC
Read the original article
Hit count: 310
Consider the following snippet:
puts 'hello'.gsub(/.+/, '\0 \\0 \\\0 \\\\0')
This prints (as seen on ideone.com):
hello hello \0 \0
This was very surprising, because I'd expect to see something like this instead:
hello \0 \hello \\0
My argument is that \
is an escape character, so you write \\
to get a literal backslash, thus \\0
is a literal backslash \
followed by 0
, etc. Obviously this is not how gsub
is interpreting it, so can someone explain what's going on?
And what do I have to do to get the replacement I want above?
© Stack Overflow or respective owner