考虑代码:
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/