Escaping a backslash in a regex

I wanna replace string title from “T8/2024” to “T9/2024”

from topic 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

But i get error:

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

If the word you want to replace has the character “/”, how should we handle it?

I don’t know off hand if this would work or not

Since you want to only replace “T8” with “T9”. Maybe remove all slashes and test?

In your syntax error it shows your missing quotes

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

Maybe try this fixed missing quotes

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

Also removed extra “/”

1 Like

Escape it with \:

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

Everything is smooth. Thank you so much, :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 "oops, something broke."
  end
end
1 Like

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