Suppose I said £
character as dangerous, and I want to be able to protect and to unprotect any string. And vice versa.
Example 1:
"Foobar £ foobar foobar foobar." # => dangerous string
"Foobar \£ foobar foobar foobar." # => protected string
Example 2:
"Foobar £ foobar £££££££foobar foobar." # => dangerous string
"Foobar \£ foobar \£\£\£\£\£\£\£foobar foobar." # => protected string
Example 3:
"Foobar \£ foobar \\£££££££foobar foobar." # => dangerous string
"Foobar \£ foobar \\\£\£\£\£\£\£\£foobar foobar." # => protected string
Is there an easy way, with Ruby, to escape (and unescape) a given character (such as £
in my example) from a string?
Edit: here is an explication about the behavior of this question.
First of all, thanks for your answers. I have a Rails app with a Tweet
model having a content
field. Example of tweet:
tweet = Tweet.create(content: "Hello @bob")
Inside the model, there's a serialization process that converte the string like this:
dump('Hello @bob') # => '["Hello £", 42]'
# ... where 42 is the id of bob username
Then, I'm able to deserialize and display its tweet like this:
load('["Hello £", 42]') # => 'Hello @bob'
In the same way, it's also possible to do so with more than one username:
dump('Hello @bob and @joe!') # => '["Hello £ and £!", 42, 185]'
load('["Hello £ and £!", 42, 185]') # => 'Hello @bob and @joe!'
That's the goal :)
But this find-and-replace could be hard to perform with something like:
tweet = Tweet.create(content: "£ Hello @bob")
'cause here we also have to escape £
char. And I think your solution is good for this. So the result become:
dump('£ Hello @bob') # => '["\£ Hello £", 42]'
load('["\£ Hello £", 42]') # => '£ Hello @bob'
Just perfect. <3 <3
Now, if there is this:
tweet = Tweet.create(content: "\£ Hello @bob")
I think we first should escape every \
, and then escape every £
, like:
dump('\£ Hello @bob') # => '["\\£ Hello £", 42]'
load('["\\£ Hello £", 42]') # => '£ Hello @bob'
However... how can we do in this case:
tweet = Tweet.create(content: "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\£ Hello @bob")
...where tweet.content.gsub(/(?<!\\)(?=(?:\\\\)*£)/, "\\")
seems not working.