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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -