正则表达式插入带有非转义\字符的变量

Pre*_*onM 1 ruby regex

我有以下尝试解析 Unrar 提取 .rar 的输出。我有以下行抛出错误:太短转义序列。这是因为变量extractLocation等于带有未转义的 \ 字符的文件路径(例如 I:\Rar\Backups\)。有没有办法在我的正则表达式中引用此变量的文字字符串解释?如果没有,我可以采取哪些其他方法来解决这个问题?

stdoutArr = stdout.split("\n")

stdoutArr.each do |line|
#line below is throwing the error   
if line.match(/((?<=(Extracting  #{extractLocation})).*.bak)/)
        extractedFile = line[(/((?<=(Extracting  #{extractLocation})).*.bak)/)]
    end
end
Run Code Online (Sandbox Code Playgroud)

aku*_*uhn 5

尝试这个

regexp = /((?<=(Extracting  #{Regexp.escape(extractLocation)})).*.bak)/
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?

  • Regexp.escape(...)转义所有特殊字符