在正则表达式中转义反斜杠

我想将字符串标题从“T8/2024”替换为“T9/2024”

来自话题 How to replace a string/character in topic title? - #11 by pfaffman

Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
  topic.title.gsub!(/T8\/2024/,"T9/2024")
  topic.fancy_title.gsub!(/T8\/2024/,"T9/2024")
  topic.slug.gsub!(/T8\/2024/,"T9/2024")
  puts topic.title
  begin
    topic.save!
  rescue
    puts "oops, something broke."
  end
end

但我收到了错误:

SyntaxError: unexpected integer literal, expecting ')'
  topic.title.gsub!(/T8/2024/,"T9/2024")
                        ^~~~

如果要替换的单词包含“/”字符,我们该如何处理?

我不确定这是否能奏效。

既然您只想将“T8”替换为“T9”。也许可以删除所有斜杠并进行测试?

在您的语法错误中,它显示您缺少引号

SyntaxError: unexpected integer literal, expecting ')'
  topic.title.gsub!(/T8/2024/,"T9/2024")
                        ^~~~

也许试试这个修复了缺失的引号

Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
  topic.title.gsub!("T8/2024","T9/2024")
  topic.fancy_title.gsub!(/T8/2024","T9/2024")
  topic.slug.gsub!("T8/2024","T9/2024")
  puts topic.title
  begin
    topic.save!
  rescue
    puts "oops, something broke."
  end
end

还删除了多余的“/”

1 个赞

使用 \ 进行转义:

[1] pry(main)> 'A title covering T8/2024'.gsub(/T8\/2024/, 'T9/2024')
=> "A title covering T9/2024"
6 个赞

一切都很顺利。非常感谢你,:slight_smile:

Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
  topic.title.gsub!("T8/2024","T9/2024")
  topic.fancy_title.gsub!("T8/2024","T9/2024")
  topic.slug.gsub!("T8/2024","T9/2024")
  puts topic.title
  begin
    topic.save!
  rescue
    puts "哎呀,出错了。"
  end
end
1 个赞

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.