简体   繁体   English

如何修改 Ruby 中的字符串,以便将所有撇号实例替换为反斜杠撇号

[英]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" “这是 Bobs 消息”

I'm doing this in a rails app.我在 Rails 应用程序中执行此操作。 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.如果你能告诉我你知道应该工作的 ruby​​ 方法,我将不胜感激。 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 .您可以在正则表达式中捕获 parens () ,然后您可以使用\\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有关更多信息,请参见类似示例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.尽管该变量似乎有两个反斜杠 ( \\\\ ) 实例,但当您puts该变量时,您会看到它只有一个。

(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!) (具有讽刺意味的是,如果您不以代码形式将其放在此响应中,即使 StackOverflow 也会对反斜杠进行转义……我不得不放置 3 个反斜杠以使其看起来像 2 个!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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