Escaping a backslash in a regex

AI-generated summary

In the discussion “Escaping a backslash in a regex,” huynhthai824 asked how to replace a string containing a forward slash / in a regex. They provided code that was causing a syntax error due to the unescaped / in the regex pattern.

Heliosurge suggested removing the slashes and testing, and also pointed out a missing quote in the original code. However, this approach was not necessary.

supermathie provided the correct solution, which was to escape the / with a backslash \. They demonstrated this with an example in pry:

'T8/2024'.gsub(/T8\/2024/, 'T9/2024')

huynhthai824 implemented this solution and confirmed that it worked, updating their original code to:

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

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 “/”

Escape it with \:

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

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