regex - Weird backslash substitution in Ruby -


i don't understand ruby code:

>> puts '\\ <- single backslash' # \ <- single backslash  >> puts '\\ <- 2x a, because 2 backslashes replaced'.sub(/\\/, 'aa') # aa <- 2x a, because 2 backslashes replaced 

so far, expected. if search 1 /\\/, , replace 2, encoded '\\\\', why this:

>> puts '\\ <- 1 ... replace 1 2'.sub(/\\/, '\\\\') # \ <- 1 backslash, though replace 1 2 

and then, when encode 3 '\\\\\\', 2:

>> puts '\\ <- 2 ... 1 3'.sub(/\\/, '\\\\\\') # \\ <- 2 backslashes, though replace 1 3 

anyone able understand why backslash gets swallowed in replacement string? happens on 1.8 , 1.9.

this issue because backslash (\) serves escape character regexps , strings. use special variable \& reduce number backslashes in gsub replacement string.

foo.gsub(/\\/,'\&\&\&') #for string foo replace each \ \\\ 

edit: should mention value of \& regexp match, in case single backslash.

also, thought there special way create string disabled escape character, apparently not. none of these produce 2 slashes:

puts "\\" puts '\\' puts %q{\\} puts %q{\\} puts """\\""" puts '''\\''' puts <<eof \\ eof   

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -