简体   繁体   中英

How to modify string in Ruby such that all instances of apostrophe are replaced with backslash apostrophe

I want a string such as "This is Bob's sentence" to be modified to be "This is Bob\\'s sentence"

My research seems to indicate that the following should work

"This is Bob's sentence".gsub("'", "\\\\'")

But the result I get is

"this is Bobs messages message"

I'm doing this in a rails app. Perhaps something else in the app is causing the issue? If you could please inform me of a ruby method which you know should work I would greatly appreciate it. Thanks in advance.

You can use the capture like this:

puts "This is Bob's sentence".gsub(/(\w\')/, '\1\\')
This is Bob'\s sentence

You capture in a regular expression what's inside parens () and then you can modify it with \\1 . You can have more than one capture group, they are numbered in order as they appear.

For more see similar example https://ruby-doc.org/core-2.7.0/String.html#gsub

mu 引用的每个线程太短

"This is Bob's sentence".gsub("'", "\\\\\\\\\\'")

This is annoying, but here's a solution that works:

sentence = "This is Bob's sentence"
sent_arr = sentence.gsub("'", "\\").split('')
sent_arr.each_index.select{|i| sent_arr[i] == "\\"}.each{|i| sent_arr.insert(i+1, "'") }
final_sentence = sent_arr.join
puts final_sentence

Basically:

  1. Replace "'" with "\\\\" (which is counted as only one index), make an array out of it.
  2. Find each index of "\\\\" in the array, insert a "'" at the position just after each.
  3. Join the array into a string.

Even though the variable will seem to have two instances of the backslash ( \\\\ ), when you puts the variable, you'll see that it only has one.

(Ironically, even StackOverflow escapes the backslashes in this response if you don't put it in code form... I had to put 3 backslashes to make it look like 2!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM