정규식에서 백슬래시 이스케이핑

문자열 제목을 "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] pry(main)> 'A title covering T8/2024'.gsub(/T8\/2024/, 'T9/2024')
=> "A title covering T9/2024"

모든 것이 순조롭습니다. 정말 감사합니다. :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