Phil R
Phil R

Reputation: 423

Ruby Regex Half Backslashes While Preserving Line Feeds

I have the following string:

coolStr = '<!--  \\n    @author       Phil R\\n    @date         6.5.2012\\n    @description  Me T\\\\nesting S\\\\\\\\ntuff\\n-->'

This string has appears to have been doubly escaped. I'd like to turn the string into:

newCoolStr = "<!--  \n    @author       Phil R\n    @date         6.5.2012\n    @description  Me T\\nesting S\\\\ntuff\n-->"

So that if you wrote:

puts newCoolStr

You would get:

<!--  
    @author       Phil R
    @date         6.5.2012
    @description  Me T\nesting S\\ntuff
-->

I've been failing to do this. The closest I can get is being able to half the backslashes with:

coolStr.gsub(/\\\\/) {'\\'}

But for reasons I don't understand this does not catch instances of "\\n" and then you end up in this scenario where there is no distinction between line feeds and what originally displayed as "\\\\n". Example being:

<!--  \\n    @author       Phil R\\n    @date         6.5.2012\\n    @description  Me T\\nesting S\\\\ntuff\\n-->

Seems like a fairly simple problem but I just can't seem to get it. Whats the best way of achieving this?

Upvotes: 0

Views: 89

Answers (2)

calvin
calvin

Reputation: 347

One issue is that the newline in your string is not a newline according to ruby. It's an escaped backslash adjacent to an n character.

You could

gsub(/\\+n/,"\n")

But you'd need a way to differentiate a desired newlines from the stuff in description that you don't want escaped. That's more tied to your app.

In this case, you could do a quick an dirty and say if the newline is followed by a word character, treat it as text.

str =  "coolStr = '<!--  \\n    @author       Phil R\\n    @date         6.5.2012\\n    @description  Me T\\\\nesting S\\\\\\\\ntuff\\n-->'"

puts str.gsub(/\\+n(?!\w)/,"\n")

coolStr = '<!--  
@author       Phil R
@date         6.5.2012
@description  Me T\\nesting S\\\\ntuff
-->'

Upvotes: 1

Phil R
Phil R

Reputation: 423

I have come across GreyCat's solution to:

How do I unescape c-style escape sequences from ruby?

This is exactly what I needed. It removes the double escaping and solves my problem. Upvoted GreyCat's solution and marking this as the answer to my own question.

Upvotes: 0

Related Questions