【发布时间】:2019-10-07 00:00:20
【问题描述】:
考虑代码:
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
【问题讨论】:
标签: ruby string replace escaping