1

These \\n are showing up in my strings even though it should only be \n.

But if I do this :

"\n".gsub('\\n','\b')

It returns :

"\n"

Ideally, I'm trying to find a regex that could rewrite this string :

"R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\\nZjTX\\n"

To not display two backslashes, but just one like this :

"R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\nZjTX\n"

But any of the regex I do will not work. I can gsub out the \n and put something like X there, but if I put a \ in it, then Ruby escapes it with an additional \ which consequentially destroys my encryption module as it needs to be specific.

Any ideas?

Trip
  • 26,756
  • 46
  • 158
  • 277

1 Answers1

3

You are falling into the trap of a different meaning of escapes when used in strings with double quotes vs single quotes. Double-quoted strings allow escape characters to be used. Thus, here "\n" actually is a one-character string containing a single line feed. Compare that to '\n' which is a two-character string containing a literal backslash followed by a character n.

This explains, whey your gsub doesn't match. If you use the following code, it should work:

"\\n".gsub('\n','\b')

For your actual issue, you can use this

string = "R3pQvDqmz/EQ7zho2mhIeE6UB4dLa6GUH7173VEMdGCcdsRm5pernkqCgbnj\\nZjTX\\n"
new_string = string.gsub("\\n", "\n")
Holger Just
  • 52,918
  • 14
  • 115
  • 123
  • +1 To further clarify the first case: `"\n".gsub("\n",'\b')` results in `"\\b"`. – Matt Mar 13 '14 at 17:44
  • It was a bit unclear what Trip actually wanted to achieve with his first example. The code I used matches his data so I chose this. Your example works too. The point is, he tried to match different things and thus didn't get the result he expected. – Holger Just Mar 13 '14 at 17:47