gsub - Replacing `\` with `\\` in ruby -


i'm trying replace occurrences of \ \\. here first try:

> puts '\\'.gsub('\\', '\\\\') \ 

i pretty surprised when saw output. after experimenting able wanted this code:

> puts '\\'.gsub('\\', '\\\\\\') \\ 

why isn't first piece of code working? why need 6 backslashes?

'\\'.gsub('\\', '\\\\') 

when substitution occurs, substitution string '\\\\' passed regexp engine, , \\ replaced \. substitution string ends '\\', single backslash.


the idomatic way replace single bachslach double use:

str.gsub(/\\/, '\\\\\\\\\')  # 8 backslashes! 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -