ruby - 如何在 Ruby 中不使用反斜杠转义来执行字符串替换

标签 ruby string replace escaping

考虑代码:

output = `cat test.txt`
puts output  # /^\\([0-3][0-9]\\/[0-1][0-9]\\/[2-9][0-9]{3}\\)$/
str = 'test ' + output
puts str     # test /^\\([0-3][0-9]\\/[0-1][0-9]\\/[2-9][0-9]{3}\\)$/
new_str = 'new test ' + output
puts new_str # new test /^\\([0-3][0-9]\\/[0-1][0-9]\\/[2-9][0-9]{3}\\)$/

res = str.sub('test', 'new test')
puts res     # new test /^\\([0-3][0-9]\\/[0-1][0-9]\\/[2-9][0-9]{3}\\)$/ <-- all fine
res = str.sub(str, new_str)
puts res     # new test /^\([0-3][0-9]\/[0-1][0-9]\/[2-9][0-9]{3}\)$/     <-- !!! problem

代码只是为了展示我遇到的问题;)

问题:我有带双反斜杠的替换文本,我需要“按原样”写入另一个文件

问题是:是否有任何不解释反斜杠的简单替换方法(可能是某种二进制模式)?

因为这样做有点奇怪:res = str.sub(str, new_str.gsub('\\', '\\\\\\\\')),虽然这有效...

真正的工作代码:

file = 'some/random/file.php'
contents = new_contents = ''
File.open(file, 'rb') do |f|
  contents = new_contents = f.read
end

contents.scan(/('([A-Z]+)' \=\> \<\<\<'JSON'(.*?)JSON)/m) do |match|
  Dir.glob("*#{match[1]}.json") do |filename|
    compressed = `../compress.py #{filename}`.gsub('\\', '\\\\\\\\')
    replacement = match[0].sub(match[2], "\n" + compressed).force_encoding('ASCII-8BIT')

    new_contents = new_contents.sub(match[0], replacement.gsub('\\', '\\\\\\\\'))
  end
end

File.open(file, 'wb') do |f|
  f.write(new_contents)
end

最佳答案

最终我找到了非常简单的解决方案:

input = '{"regex": "/^\\\\([0-3][0-9]\\\\)$/"}'
puts input # gives => {"regex": "/^\\([0-3][0-9]\\)$/"}

search = '/^\\\\([0-3][0-9]\\\\)$/'
replace = '/^\\\\([0-9]\\\\)$/'

puts input.sub(search, replace) # gives => {"regex": "/^\([0-9]\)$/"}, which is wrong result

input[search] = replace # <-- here is the trick, but makes changes in place
puts input # gives => {"regex": "/^\\([0-9]\\)$/"} => success!

但是!如果您的字符串不包含任何 search 子字符串,您将得到一个 string not matched (IndexError)

所以你可能想像这样保护你的代码:

input[search] = replace if input.include? search

另外,如果你想保持你的input不变,你可以.dup它到另一个变量:

new_input = input.dup
new_input[search] = replace if new_input.include? search

关于ruby - 如何在 Ruby 中不使用反斜杠转义来执行字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223924/

相关文章:

ruby-on-rails - 有没有更有效的方法来存储商店的营业时间?

ruby - 无法加载 'active_record/connection_adapters/mysql2_adapter'

java - 查找 String 数组中索引处元素的子字符串

java - 为什么 String + '\u0000' 与 String 不同?

C++ string::find 崩溃应用程序

c# - 将动态值传递给 C# 正则表达式中的量词

ruby - 如何调用或激活一个类?

python - str.replace 在函数中不起作用

python - 如何使用 Pandas 替换列中的元素

ruby - 在测试中创建和删除文件夹