regex - Ruby Regexp: How do I replace doubly escaped characters such as \\n with \n -



regex - Ruby Regexp: How do I replace doubly escaped characters such as \\n with \n -

so, have

puts "test\\nstring".gsub(/\\n/, "\n")

and works.

but how write 1 statement replaces \n, \r, , \t correctly escaped counterparts?

those aren't escaped characters, literal characters represented beingness escaped they're human readable. need this:

escapes = { 'n' => "\n", 'r' => "\r", 't' => "\t" } "test\\nstring".gsub(/\\([nrt])/) { escapes[$1] } # => "test\nstring"

you have add together other escape characters required, , still won't accommodate of more obscure ones if need interpret them all. potentially unsafe simple solution eval it:

eval("test\\nstring")

so long can assured input stream doesn't contain things #{ ... } allow injecting arbitrary ruby, possible if 1 shot repair prepare damaged encoding, fine.

update

there might mis-understanding these backslashes are. here's example:

"\n".bytes.to_a # => [10] "\\n".bytes.to_a # => [92, 110]

you can see these 2 exclusively different things. \n representation of ascii character 10, linefeed.

ruby regex

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -