regex - Smart conversion of double to single quotes in ruby -


problem

in source file, have large number of strings. interpolation, special symbols , neither.

i trying work out if can replace simple strings' double quotes single quotes whilst leaving double quotes interpolated , special symbol strings. run conversion on 1 or more source code files.

i imagine there nice regex this, can't quite formulate it.

example - code

imagine following code:

def myfunc(var, var2 = "abc")   s = "something"   puts "a simple string"   puts "string single ' quote"   puts "string newline \n"     puts "my #{var}" end 

example - result

i turn this:

def myfunc(var, var2 = 'abc')   s = 'something'   puts 'a simple string'   puts "string single ' quote"   puts "string newline \n"     puts "my #{var}" end 

if has ideas i'd grateful!

assuming can read string file array strings:

strings = [ "\"a simple string\"",             "\"string single ' quote\"",             "\"string newline \n\""             "\"my \#{var}\"" ] 

then eval them see how behave:

$safe = 4 single_quoted_when_possible = strings.map { |double_quoted|   begin     string = eval( double_quoted ) # string, ruby sees     raise unless string.is_a? string     raise unless '"' + string + '"' == double_quoted   rescue     raise "array element not string!"   end   begin       raise unless eval( "'#{string}'" ) == string     "'#{string}'"   rescue     double_quoted   end } 

and safe level 4 woodoo, acknowledgement me doing dangerous. not know extent protects against dangers.

in particular case, can create regexp heuristic, relying on hope nobody write "evil" strings in code, such /= *(".+") *$/ or /\w+ *\(* *(".+") *\)* *$/. heuristic extract string suspects, further apply method wrote higher above. still have human @ each replacement, , run tests on resulting code afterwards.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -