1

问题

在源文件中,我有大量带有插值的 strings.ome,有些带有特殊符号,有些则没有。

我正在尝试确定是否可以在转换转义的单引号字符时用双引号替换单引号。然后,我将对一个或多个源代码文件运行此转换。

示例 - 代码

想象一下下面的代码:

def myfunc(var, var2 = 'abc')
  s = 'something'
  puts 'a simple string'
  puts 'string with an escaped quote \' in it'
  x = "nasty #{interpolated}" + s + ' and single quote combo'
  puts "my #{var}"
end

示例 - 结果

我想把它变成这样:

def myfunc(var, var2 = "abc")
  s = "something"
  puts "a simple string"
  puts "string with an escaped quote ' in it"
  x = "nasty #{interpolated}" + s + " and single quote combo"
  puts "my #{var}"
end

如果有人有任何想法,我将不胜感激!

4

2 回答 2

3

您希望在(?<!)运算符后面进行负面观察:

正则表达式

 (?<!\)'

演示

http://regex101.com/r/rN5eE6

解释

  • 您想替换任何前面没有反斜杠的单引号。
  • 不要忘记查找并替换所有\'内容'

还有更多

For this use case, even if it's a simple use case, a ruby parser would perform better.

于 2013-05-14T12:34:01.020 回答
2

As Peter Hamilton pointed out, although replacing single quoted strings with double quoted equivalents might seem as an easy task at first, even that cannot be done easily, if at all, with regexen, mainly thanks to the possibility of single quotes in the "wrong places", such as within double-quoted strings, %q literal string constructs, heredocs, comments...

x = 'puts "foo"'
y = %/puts 'foo'/ # TODO: Replace "x = %/puts 'foo'/" with "x = %#puts 'bar'#"

But the correct solution, in this case, is much easier than the other way around (double quoted to single quoted), and actually partially attainable:

require 'ripper'
require 'sorcerer' # gem install sorcerer if necessary
my_source = <<-source
  x = 'puts "foo"'
  y = "puts 'bar'"
source
sexp = Ripper::SexpBuilder.new( my_source ).parse
double_quoted_source = Sorcerer.source sexp
#=> "x = \"puts \"foo\"\"; y = \"puts 'bar'\""

The reason why I say "partially attainable" is because, as you can see by yourself,

puts double_quoted_source
#=> x = "puts "foo""; y = "puts 'bar'"

Sorcerer forgets to escape double quotes inside formerly single-quoted string. Feel free to submit a patch to sorcerer's author Jim Weirich that would fix the problem.

于 2013-05-16T12:08:16.727 回答